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

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

   Copyright (C) 1996, 1997 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: Specialized Two-Dimensional Plots,  Next: Three-Dimensional Plotting,  Prev: Two-Dimensional Plotting,  Up: Plotting

17.2 Specialized Two-Dimensional Plots
======================================

 -- Function File:  bar (X, Y)
     Given two vectors of x-y data, `bar' produces a bar graph.

     If only one argument is given, it is taken as a vector of y-values
     and the x coordinates are taken to be the indices of the elements.

     If two output arguments are specified, the data are generated but
     not plotted.  For example,

          bar (x, y);

     and

          [xb, yb] = bar (x, y);
          plot (xb, yb);

     are equivalent.

 -- Function File:  contour (Z, N)
 -- Function File:  contour (X, Y, Z, N)
     Make a contour plot of the three-dimensional surface described by
     Z.  Someone needs to improve `gnuplot''s contour routines before
     this will be very useful.

 -- Function File:  hist (Y, X, NORM)
     Produce histogram counts or plots.

     With one vector input argument, plot a histogram of the values with
     10 bins.  The range of the histogram bins is determined by the
     range of the data.

     Given a second scalar argument, use that as the number of bins.

     Given a second vector argument, use that as the centers of the
     bins, with the width of the bins determined from the adjacent
     values in the vector.

     If third argument is provided, the histogram is normalised such
     that the sum of the bars is equal to NORM.

     Extreme values are lumped in the first and last bins.

     With two output arguments, produce the values NN and XX such that
     `bar (XX, NN)' will plot the histogram.

 -- Function File:  loglog (ARGS)
     Make a two-dimensional plot using log scales for both axes.  See
     the description of `plot' for a description of the arguments that
     `loglog' will accept.

 -- Function File:  polar (THETA, RHO, FMT)
     Make a two-dimensional plot given polar the coordinates THETA and
     RHO.

     The optional third argument specifies the line type.

 -- Function File:  semilogx (ARGS)
     Make a two-dimensional plot using a log scale for the X axis.  See
     the description of `plot' for a description of the arguments that
     `semilogx' will accept.

 -- Function File:  semilogy (ARGS)
     Make a two-dimensional plot using a log scale for the Y axis.  See
     the description of `plot' for a description of the arguments that
     `semilogy' will accept.

 -- Function File:  stairs (X, Y)
     Given two vectors of x-y data, bar produces a `stairstep' plot.

     If only one argument is given, it is taken as a vector of y-values
     and the x coordinates are taken to be the indices of the elements.

     If two output arguments are specified, the data are generated but
     not plotted.  For example,

          stairs (x, y);

     and

          [xs, ys] = stairs (x, y);
          plot (xs, ys);

     are equivalent.

 -- Function File:  errorbar (ARGS)
     This function produces two-dimensional plots with errorbars. Many
     different combinations of arguments are possible.  The simplest
     form is

          errorbar (Y, EY)

     where the first argument is taken as the set of Y coordinates and
     the second argument EY is taken as the errors of the Y values. X
     coordinates are taken to be the indices of the elements, starting
     with 1.

     If more than two arguments are given, they are interpreted as

          errorbar (X, Y, ..., FMT ...)

     where after X and Y there can be up to four error parameters such
     as EY, EX, LY, UY etc., depending on the plot type. Any number of
     argument sets may appear, as long as they are separated with a
     format string FMT.

     If Y is a matrix, X and error parameters must also be matrices
     having same dimensions. The columns of Y are plotted versus the
     corresponding columns of X and errorbars are drawn from the
     corresponding columns of error parameters.

     If FMT is missing, yerrorbars ("~") plot style is assumed.  If the
     FMT argument is supplied, it is interpreted as in normal plots
     (See __pltopt__). In addition the following plot styles are
     supported by errorbar:

    `~'
          Set yerrorbars plot style (default).

    `>'
          Set xerrorbars plot style.

    `~>'
          Set xyerrorbars plot style.

    `#'
          Set boxes plot style.

    `#~'
          Set boxerrorbars plot style.

    `#~>'
          Set boxxyerrorbars plot style.


     Examples:

          errorbar(X, Y, EX, ">")

     xerrorbar plot of Y versus X with X errorbars drawn from X-EX to
     X+EX.

          errorbar(X, Y1, EY, "~", X, Y2, LY, UY)

     Two yerrorbar plots with Y1 and Y2 versus X.  Errorbars for Y1 are
     drawn from Y1-EY to Y1+EY, errorbars for Y2 from Y2-LY to Y2+UY.

          errorbar(X, Y, LX, UX, LY, UY, "~>")

     xyerrorbar plot of Y versus X where X errorbars are drawn from
     X-LX to X+UX and Y errorbars from Y-LY to Y+UY.


 -- Function File:  loglogerr (ARGS)
     This function produces two-dimensional plots on double logarithm
     axis with errorbars. Many different combinations of arguments are
     possible.  The most used form is

          loglogerr (X, Y, EY, FMT)

     which produces a double logarithm plot of Y versus X with errors
     in the Y-scale defined by EY and the plot format defined by FMT.
     See errorbar for available formats and additional information.


 -- Function File:  semilogxerr (ARGS)
     This function produces two-dimensional plots on a semilogarithm
     axis with errorbars. Many different combinations of arguments are
     possible.  The most used form is

          semilogxerr (X, Y, EY, FMT)

     which produces a semi-logarithm plot of Y versus X with errors in
     the Y-scale defined by EY and the plot format defined by FMT. See
     errorbar for available formats and additional information.


 -- Function File:  semilogyerr (ARGS)
     This function produces two-dimensional plots on a semilogarithm
     axis with errorbars. Many different combinations of arguments are
     possible.  The most used form is

          semilogyerr (X, Y, EY, FMT)

     which produces a semi-logarithm plot of Y versus X with errors in
     the Y-scale defined by EY and the plot format defined by FMT. See
     errorbar for available formats and additional information.



File: octave.info,  Node: Three-Dimensional Plotting,  Next: Plot Annotations,  Prev: Specialized Two-Dimensional Plots,  Up: Plotting

17.3 Three-Dimensional Plotting
===============================

The MATLAB-style three-dimensional plotting commands are:

 -- Function File:  mesh (X, Y, Z)
     Plot a mesh given matrices X, and Y from `meshdom' and a matrix Z
     corresponding to the X and Y coordinates of the mesh.  If X and Y
     are vectors, then a typical vertex is (X(j), Y(i), Z(i,j)).  Thus,
     columns of Z correspond to different X values and rows of Z
     correspond to different Y values.

 -- Function File: [XX, YY] = meshgrid (X, Y)
 -- Function File: [XX, YY] = meshgrid (X)
     Given vectors of X and Y coordinates, return two matrices
     corresponding to the X and Y coordinates of a mesh.  The rows of
     XX are copies of X, and the columns of YY are copies of Y.

 -- Function File:  meshdom (X, Y)
     Given vectors of X and Y coordinates, return two matrices
     corresponding to the X and Y coordinates of the mesh.

     Note: this function is provided for compatibility with older
     versions of MATLAB.  You should use `meshgrid' instead.


File: octave.info,  Node: Plot Annotations,  Next: Multiple Plots on One Page,  Prev: Three-Dimensional Plotting,  Up: Plotting

17.4 Plot Annotations
=====================

 -- Function File:  grid (ARG)
     For two-dimensional plotting, force the display of a grid on the
     plot.  The argument may be either `"on"' or `"off"'.  If it is
     omitted, `"on"' is assumed.

 -- Function File:  title (STRING)
     Specify a title for a plot.

 -- Function File:  xlabel (STRING)
 -- Function File:  ylabel (STRING)
 -- Function File:  zlabel (STRING)
     Specify x, y, and z axis labels for the plot.  If you already have
     a plot displayed, use the command `replot' to redisplay it with
     the new labels.

 -- Function File:  top_title (STRING)
 -- Function File:  bottom_title (STRING)
     Makes a title with text STRING at the top (bottom) of the plot.


File: octave.info,  Node: Multiple Plots on One Page,  Next: Multiple Plot Windows,  Prev: Plot Annotations,  Up: Plotting

17.5 Multiple Plots on One Page
===============================

The following functions all require a version of `gnuplot' that
supports the multiplot feature.

 -- Function File:  mplot (X, Y)
 -- Function File:  mplot (X, Y, FMT)
 -- Function File:  mplot (X1, Y1, X2, Y2)
     This is a modified version of the `plot' function that works with
     the multiplot version of `gnuplot' to plot multiple plots per page.
     This plot version automatically advances to the next subplot
     position after each set of arguments are processed.

     See the description of the PLOT function for the various options.

 -- Function File:  multiplot (XN, YN)
     Sets and resets multiplot mode.

     If the arguments are non-zero, `multiplot' will set up multiplot
     mode with XN, YN subplots along the X and Y axes.  If both
     arguments are zero, `multiplot' closes multiplot mode.

 -- Function File:  oneplot ()
     If in multiplot mode, switches to single plot mode.

 -- Function File:  plot_border (...)
     Multiple arguments allowed to specify the sides on which the border
     is shown.  Allowed arguments include:

    `"blank"'
          No borders displayed.

    `"all"'
          All borders displayed

    `"north"'
          North Border

    `"south"'
          South Border

    `"east"'
          East Border

    `"west"'
          West Border

     The arguments may be abbreviated to single characters.  Without any
     arguments, `plot_border' turns borders off.

 -- Function File:  subplot (ROWS, COLS, INDEX)
 -- Function File:  subplot (RCN)
     Sets `gnuplot' in multiplot mode and plots in location given by
     index (there are COLS by ROWS subwindows).

     The global variable __MULTIPLOT_SCALE__ should be used when the
     command `__gnuplot_set__ size xsize, ysize' has been used prior to
     calling `subplot'.

     The value of __MULTIPLOT_SCALE__ should be a vector with two
     elements, the first set equal to XSIZE and the second to YSIZE.

     Input:

    ROWS
          Number of rows in subplot grid.

    COLUMNS
          Number of columns in subplot grid.

    INDEX
          Index of subplot where to make the next plot.

     If only one argument is supplied, then it must be a three digit
     value specifying the location in digits 1 (rows) and 2 (columns)
     and the plot index in digit 3.

     The plot index runs row-wise.  First all the columns in a row are
     filled and then the next row is filled.

     For example, a plot with 4 by 2 grid will have plot indices
     running as follows:
          +----+----+----+----+
          |  1  |  2  |  3  |  4  |
          +----+----+----+----+
          |  5  |  6  |  7  |  8  |
          +----+----+----+----+

 -- Function File:  subwindow (XN, YN)
     Sets the subwindow position in multiplot mode for the next plot.
     The multiplot mode has to be previously initialized using the
     `multiplot' function, otherwise this command just becomes an alias
     to `multiplot'


File: octave.info,  Node: Multiple Plot Windows,  Next: Low-Level plotting commands,  Prev: Multiple Plots on One Page,  Up: Plotting

17.6 Multiple Plot Windows
==========================

 -- Function File:  figure (N)
     Set the current plot window to plot window N.  This function
     currently requires X11 and a version of gnuplot that supports
     multiple frames.  If N is not specified, the next available window
     number is chosen.


File: octave.info,  Node: Low-Level plotting commands,  Next: Interaction with gnuplot,  Prev: Multiple Plot Windows,  Up: Plotting

17.7 Low-Level plotting commands
================================

 -- Command: gplot RANGES EXPRESSION USING TITLE STYLE
     Generate a 2-dimensional plot.

     The RANGES, USING, TITLE, and STYLE arguments are optional, and
     the USING, TITLE and STYLE qualifiers may appear in any order
     after the expression.  You may plot multiple expressions with a
     single command by separating them with commas.  Each expression
     may have its own set of qualifiers.

     The optional item RANGES has the syntax

          [ x_lo : x_up ] [ y_lo : y_up ]

     and may be used to specify the ranges for the axes of the plot,
     independent of the actual range of the data.  The range for the y
     axis and any of the individual limits may be omitted.  A range
     `[:]' indicates that the default limits should be used.  This
     normally means that a range just large enough to include all the
     data points will be used.

     The expression to be plotted must not contain any literal matrices
     (e.g. `[ 1, 2; 3, 4 ]') since it is nearly impossible to
     distinguish a plot range from a matrix of data.

     See the help for `gnuplot' for a description of the syntax for the
     optional items.

     By default, the `gplot' command plots the second column of a matrix
     versus the first.  If the matrix only has one column, it is taken
     as a vector of y-coordinates and the x-coordinate is taken as the
     element index, starting with zero.  For example,

          gplot rand (100,1) with linespoints

     will plot 100 random values and connect them with lines.  When
     `gplot' is used to plot a column vector, the indices of the
     elements are taken as x values.

     If there are more than two columns, you can choose which columns
     to plot with the USING qualifier. For example, given the data

          x = (-10:0.1:10)';
          data = [x, sin(x), cos(x)];

     the command

          gplot [-11:11] [-1.1:1.1] \
            data with lines, data using 1:3 with impulses

     will plot two lines.  The first line is generated by the command
     `data with lines', and is a graph of the sine function over the
     range -10 to 10.  The data is taken from the first two columns of
     the matrix because columns to plot were not specified with the
     USING qualifier.

     The clause `using 1:3' in the second part of this plot command
     specifies that the first and third columns of the matrix `data'
     should be taken as the values to plot.

     In this example, the ranges have been explicitly specified to be a
     bit larger than the actual range of the data so that the curves do
     not touch the border of the plot.

 -- Command: gsplot RANGES EXPRESSION USING TITLE STYLE
     Generate a 3-dimensional plot.

     The RANGES, USING, TITLE, and STYLE arguments are optional, and
     the USING, TITLE and STYLE qualifiers may appear in any order
     after the expression.  You may plot multiple expressions with a
     single command by separating them with commas.  Each expression
     may have its own set of qualifiers.

     The optional item RANGES has the syntax

          [ x_lo : x_up ] [ y_lo : y_up ] [ z_lo : z_up ]

     and may be used to specify the ranges for the axes of the plot,
     independent of the actual range of the data.  The range for the y
     and z axes and any of the individual limits may be omitted.  A
     range `[:]' indicates that the default limits should be used.  This
     normally means that a range just large enough to include all the
     data points will be used.

     The expression to be plotted must not contain any literal matrices
     (e.g.  `[ 1, 2; 3, 4 ]') since it is nearly impossible to
     distinguish a plot range from a matrix of data.

     See the help for `gnuplot' for a description of the syntax for the
     optional items.

     By default, the `gsplot' command plots each column of the
     expression as the z value, using the row index as the x value, and
     the column index as the y value.  The indices are counted from
     zero, not one.  For example,

          gsplot rand (5, 2)

     will plot a random surface, with the x and y values taken from the
     row and column indices of the matrix.

     If parametric plotting mode is set (using the command `gset
     parametric', then `gsplot' takes the columns of the matrix three
     at a time as the x, y and z values that define a line in three
     space.  Any extra columns are ignored, and the x and y values are
     expected to be sorted.  For example, with `parametric' set, it
     makes sense to plot a matrix like

          1 1 3 2 1 6 3 1 9
          1 2 2 2 2 5 3 2 8
          1 3 1 2 3 4 3 3 7

     but not `rand (5, 30)'.

 -- Command: replot options
     The `replot' command allows you to force the plot to be
     redisplayed.  This is useful if you have changed something about
     the plot, such as the title or axis labels.  The `replot' command
     also accepts the same arguments as `gplot' or `gsplot' (except for
     data ranges) so you can add additional lines to existing plots.

     For example,

          gset term tek40
          gset output "/dev/plotter"
          gset title "sine with lines and cosine with impulses"
          replot "sin (x) w l"

     will change the terminal type for plotting, add a title to the
     current plot, add a graph of sin (x) to the plot, and force the
     new plot to be sent to the plot device.  This last step is
     normally required in order to update the plot.  This default is
     reasonable for slow terminals or hardcopy output devices because
     even when you are adding additional lines with a replot command,
     gnuplot always redraws the entire plot, and you probably don't
     want to have a completely new plot generated every time something
     as minor as an axis label changes.

     The command `shg' is equivalent to executing `replot'.

   Note that NaN values in the plot data are automatically omitted, and
Inf values are converted to a very large value before calling gnuplot.


File: octave.info,  Node: Interaction with gnuplot,  Prev: Low-Level plotting commands,  Up: Plotting

17.8 Interaction with `gnuplot'
===============================

 -- Built-in Variable: gnuplot_binary
     The name of the program invoked by the plot command.  The default
     value is `"gnuplot"'.  *Note Installation::.

 -- Built-in Variable: gnuplot_has_frames
     If the value of this variable is nonzero, Octave assumes that your
     copy of gnuplot has support for multiple frames that is included
     in recent 3.6beta releases.  Its initial value is determined by
     configure, but it can be changed in your startup script or at the
     command line in case configure got it wrong, or if you upgrade
     your gnuplot installation.

 -- Built-in Variable: gnuplot_command_plot

 -- Built-in Variable: gnuplot_command_replot

 -- Built-in Variable: gnuplot_command_splot

 -- Built-in Variable: gnuplot_command_using

 -- Built-in Variable: gnuplot_command_with

 -- Built-in Variable: gnuplot_command_axes

 -- Built-in Variable: gnuplot_command_title

 -- Built-in Variable: gnuplot_command_end


File: octave.info,  Node: Matrix Manipulation,  Next: Arithmetic,  Prev: Plotting,  Up: Top

18 Matrix Manipulation
**********************

There are a number of functions available for checking to see if the
elements of a matrix meet some condition, and for rearranging the
elements of a matrix.  For example, Octave can easily tell you if all
the elements of a matrix are finite, or are less than some specified
value.  Octave can also rotate the elements, extract the upper- or
lower-triangular parts, or sort the columns of a matrix.

* Menu:

* Finding Elements and Checking Conditions::
* Rearranging Matrices::
* Special Utility Matrices::
* Famous Matrices::


File: octave.info,  Node: Finding Elements and Checking Conditions,  Next: Rearranging Matrices,  Up: Matrix Manipulation

18.1 Finding Elements and Checking Conditions
=============================================

The functions `any' and `all' are useful for determining whether any or
all of the elements of a matrix satisfy some condition.  The `find'
function is also useful in determining which elements of a matrix meet
a specified condition.

 -- Built-in Function:  any (X, DIM)
     For a vector argument, return 1 if any element of the vector is
     nonzero.

     For a matrix argument, return a row vector of ones and zeros with
     each element indicating whether any of the elements of the
     corresponding column of the matrix are nonzero.  For example,

          any (eye (2, 4))
               => [ 1, 1, 0, 0 ]

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

          any (eye (2, 4), 2)
               => [ 1; 1 ]

 -- Built-in Function:  all (X, DIM)
     The function `all' behaves like the function `any', except that it
     returns true only if all the elements of a vector, or all the
     elements along dimension DIM of a matrix, are nonzero.

   Since the comparison operators (*note Comparison Ops::) return
matrices of ones and zeros, it is easy to test a matrix for many
things, not just whether the elements are nonzero.  For example,

     all (all (rand (5) < 0.9))
          => 0

tests a random 5 by 5 matrix to see if all of its elements are less
than 0.9.

   Note that in conditional contexts (like the test clause of `if' and
`while' statements) Octave treats the test as if you had typed `all
(all (condition))'.

 -- Mapping Function:  xor (X, Y)
     Return the `exclusive or' of the entries of X and Y.  For boolean
     expressions X and Y, `xor (X, Y)' is true if and only if X or Y is
     true, but not if both X and Y are true.

 -- Function File:  is_duplicate_entry (X)
     Return non-zero if any entries in X are duplicates of one another.

 -- Function File:  diff (X, K, DIM)
     If X is a vector of length N, `diff (X)' is the vector of first
     differences X(2) - X(1), ..., X(n) - X(n-1).

     If X is a matrix, `diff (X)' is the matrix of column differences
     along the first non-singleton dimension.

     The second argument is optional.  If supplied, `diff (X, K)',
     where K is a nonnegative integer, returns the K-th differences. It
     is possible that K is larger than then first non-singleton
     dimension of the matrix. In this case, `diff' continues to take
     the differences along the next non-singleton dimension.

     The dimension along which to take the difference can be explicitly
     stated with the optional variable DIM. In this case the K-th order
     differences are calculated along this dimension.  In the case
     where K exceeds `size (X, DIM)' then an empty matrix is returned.

 -- Mapping Function:  isinf (X)
     Return 1 for elements of X that are infinite and zero otherwise.
     For example,

          isinf ([13, Inf, NA, NaN])
               => [ 0, 1, 0, 0 ]

 -- Mapping Function:  isnan (X)
     Return 1 for elements of X that are NaN values and zero otherwise.
     For example,

          isnan ([13, Inf, NA, NaN])
               => [ 0, 0, 0, 1 ]

 -- Mapping Function:  finite (X)
     Return 1 for elements of X that are finite values and zero
     otherwise. For example,

          finite ([13, Inf, NA, NaN])
               => [ 1, 0, 0, 0 ]

 -- Loadable Function:  find (X)
     Return a vector of indices of nonzero elements of a matrix.  To
     obtain a single index for each matrix element, Octave pretends
     that the columns of a matrix form one long vector (like Fortran
     arrays are stored).  For example,

          find (eye (2))
               => [ 1; 4 ]

     If two outputs are requested, `find' returns the row and column
     indices of nonzero elements of a matrix.  For example,

          [i, j] = find (2 * eye (2))
               => i = [ 1; 2 ]
               => j = [ 1; 2 ]

     If three outputs are requested, `find' also returns a vector
     containing the nonzero values.  For example,

          [i, j, v] = find (3 * eye (2))
               => i = [ 1; 2 ]
               => j = [ 1; 2 ]
               => v = [ 3; 3 ]

 -- Function File: [ERR, Y1, ...] = common_size (X1, ...)
     Determine if all input arguments are either scalar or of common
     size.  If so, ERR is zero, and YI is a matrix of the common size
     with all entries equal to XI if this is a scalar or XI otherwise.
     If the inputs cannot be brought to a common size, errorcode is 1,
     and YI is XI.  For example,

          [errorcode, a, b] = common_size ([1 2; 3 4], 5)
          => errorcode = 0
          => a = [ 1, 2; 3, 4 ]
          => b = [ 5, 5; 5, 5 ]

     This is useful for implementing functions where arguments can
     either be scalars or of common size.


File: octave.info,  Node: Rearranging Matrices,  Next: Special Utility Matrices,  Prev: Finding Elements and Checking Conditions,  Up: Matrix Manipulation

18.2 Rearranging Matrices
=========================

 -- Function File:  fliplr (X)
     Return a copy of X with the order of the columns reversed.  For
     example,

          fliplr ([1, 2; 3, 4])
          =>  2  1
                   4  3

     Note that `fliplr' only workw with 2-D arrays.  To flip N-d arrays
     use `flipdim' instead.

 -- Function File:  flipud (X)
     Return a copy of X with the order of the rows reversed.  For
     example,

          flipud ([1, 2; 3, 4])
          =>  3  4
                   1  2

     Due to the difficulty of defining which axis about which to flip
     the matrix `flipud' only work with 2-d arrays.  To flip N-d arrays
     use `flipdim' instead.

 -- Function File:  flipdim (X, DIM)
     Return a copy of X flipped about the dimension DIM.  For example

          flipdim ([1, 2; 3, 4], 2)
          =>  2  1
                   4  3

 -- Function File:  rot90 (X, N)
     Return a copy of X with the elements rotated counterclockwise in
     90-degree increments.  The second argument is optional, and
     specifies how many 90-degree rotations are to be applied (the
     default value is 1).  Negative values of N rotate the matrix in a
     clockwise direction.  For example,

          rot90 ([1, 2; 3, 4], -1)
          =>  3  1
                   4  2

     rotates the given matrix clockwise by 90 degrees.  The following
     are all equivalent statements:

          rot90 ([1, 2; 3, 4], -1)
          ==
          rot90 ([1, 2; 3, 4], 3)
          ==
          rot90 ([1, 2; 3, 4], 7)

     Due to the difficulty of defining an axis about which to rotate the
     matrix `rot90' only work with 2-D arrays.  To rotate N-d arrays
     use `rotdim' instead.

 -- Function File:  rotdim (X, N, PLANE)
     Return a copy of X with the elements rotated counterclockwise in
     90-degree increments.  The second argument is optional, and
     specifies how many 90-degree rotations are to be applied (the
     default value is 1).  The third argument is also optional and
     defines the plane of the rotation. As such PLANE is a two element
     vector containing two different valid dimensions of the matrix. If
     PLANE is not given Then the first two non-singleton dimensions are
     used.

     Negative values of N rotate the matrix in a clockwise direction.
     For example,

          rotdim ([1, 2; 3, 4], -1, [1, 2])
          =>  3  1
                   4  2

     rotates the given matrix clockwise by 90 degrees.  The following
     are all equivalent statements:

          rot90 ([1, 2; 3, 4], -1, [1, 2])
          ==
          rot90 ([1, 2; 3, 4], 3, [1, 2])
          ==
          rot90 ([1, 2; 3, 4], 7, [1, 2])

 -- Built-in Function:  cat (DIM, ARRAY1, ARRAY2, ..., ARRAYN)
     Return the concatenation of N-d array objects, ARRAY1, ARRAY2,
     ..., ARRAYN along dimension DIM.

          A = ones (2, 2);
          B = zeros (2, 2);
          cat (2, A, B)
          => ans =

               1 1 0 0
               1 1 0 0

     Alternatively, we can concatenate A and B along the second
     dimension the following way:

          [A, B].

     DIM can be larger than the dimensions of the N-d array objects and
     the result will thus have DIM dimensions as the following example
     shows:
          cat (4, ones(2, 2), zeros (2, 2))
          => ans =

             ans(:,:,1,1) =

               1 1
               1 1

             ans(:,:,1,2) =
               0 0
               0 0


 -- Built-in Function:  horzcat (ARRAY1, ARRAY2, ..., ARRAYN)
     Return the horizontal concatenation of N-d array objects, ARRAY1,
     ARRAY2, ..., ARRAYN along dimension 2.

 -- Built-in Function:  vertcat (ARRAY1, ARRAY2, ..., ARRAYN)
     Return the vertical concatenation of N-d array objects, ARRAY1,
     ARRAY2, ..., ARRAYN along dimension 1.

 -- Built-in Function:  permute (A, PERM)
     Return the generalized transpose for an N-d array object A.  The
     permutation vector PERM must contain the elements `1:ndims(a)' (in
     any order, but each element must appear just once).


 -- Built-in Function:  ipermute (A, IPERM)
     The inverse of the `permute' function.  The expression

          ipermute (permute (a, perm), perm)
     returns the original array A.


 -- Function File:  reshape (A, M, N, ...)
 -- Function File:  reshape (A, SIZ)
     Return a matrix with the given dimensions whose elements are taken
     from the matrix A.  The elements of the matrix are access in
     column-major order (like Fortran arrays are stored).

     For example,

          reshape ([1, 2, 3, 4], 2, 2)
               =>  1  3
                   2  4

     Note that the total number of elements in the original matrix must
     match the total number of elements in the new matrix.

     A single dimension of the return matrix can be unknown and is
     flagged by an empty argument.

 -- Function File: Y = circshift (X, N)
     Circularly shifts the values of the array X. N must be a vector of
     integers no longer than the number of dimensions in X. The values
     of N can be either positive or negative, which determines the
     direction in which the values or X are shifted. If an element of N
     is zero, then the corresponding dimension of X will not be
     shifted. For example

          x = [1, 2, 3; 4, 5, 6, 7, 8, 9];
          circshift (x, 1)
          =>  7, 8, 9
              1, 2, 3
              4, 5, 6
          circshift (x, -2)
          =>  7, 8, 9
              1, 2, 3
              4, 5, 6
          circshift (x, [0,1])
          =>  3, 1, 2
              6, 4, 5
              9, 7, 8

 -- Function File: Y = shiftdim (X, N)
 -- Function File: [Y, NS] = shiftdim (X)
     Shifts the dimension of X by N, where N must be an integer scalar.
     When N is negative, the dimensions of X are shifted to the left,
     with the leading dimensions circulated to the end. If N is
     positive, then the dimensions of X are shifted to the right, with
     the N singleton dimensions added.

     Called with a single argument, `shiftdim', removes the leading
     singleton dimensions, returning the number of dimensions removed
     in the second output argument NS.

     For example

          x = ones (1, 2, 3);
          size (shiftdim (x, -1))
          => [2, 3, 1]
          size (shiftdim (x, 1))
          => [1, 1, 2, 3]
          [b, ns] = shiftdim (x);
          => b =  [1, 1, 1; 1, 1, 1]
          => ns = 1

 -- Function File:  shift (X, B)
 -- Function File:  shift (X, B, DIM)
     If X is a vector, perform a circular shift of length B of the
     elements of X.

     If X is a matrix, do the same for each column of X.  If the
     optional DIM argument is given, operate along this dimension

 -- Loadable Function: [S, I] = sort (X)
 -- Loadable Function: [S, I] = sort (X, DIM)
 -- Loadable Function: [S, I] = sort (X, MODE)
 -- Loadable Function: [S, I] = sort (X, DIM, MODE)
     Return a copy of X with the elements elements arranged in
     increasing order.  For matrices, `sort' orders the elements in each
     column.

     For example,

          sort ([1, 2; 2, 3; 3, 1])
               =>  1  1
                   2  2
                   3  3

     The `sort' function may also be used to produce a matrix
     containing the original row indices of the elements in the sorted
     matrix.  For example,

          [s, i] = sort ([1, 2; 2, 3; 3, 1])
               => s = 1  1
                      2  2
                      3  3
               => i = 1  3
                      2  1
                      3  2

     If the optional argument DIM is given, then the matrix is sorted
     along the dimension defined by DIM. The optional argument `mode'
     defines the order in which the values will be sorted. Valid values
     of `mode' are `ascend' or `descend'.

     For equal elements, the indices are such that the equal elements
     are listed in the order that appeared in the original list.

     The `sort' function may also be used to sort strings and cell
     arrays of strings, it which case the dictionary order of the
     strings is used.

     The algorithm used in `sort' is optimized for the sorting of
     partially ordered lists.

   Since the `sort' function does not allow sort keys to be specified,
it can't be used to order the rows of a matrix according to the values
of the elements in various columns(1) in a single call.  Using the
second output, however, it is possible to sort all rows based on the
values in a given column.  Here's an example that sorts the rows of a
matrix based on the values in the second column.

     a = [1, 2; 2, 3; 3, 1];
     [s, i] = sort (a (:, 2));
     a (i, :)
          =>  3  1
              1  2
              2  3

 -- Function File:  tril (A, K)
 -- Function File:  triu (A, K)
     Return a new matrix formed by extracting extract the lower (`tril')
     or upper (`triu') triangular part of the matrix A, and setting all
     other elements to zero.  The second argument is optional, and
     specifies how many diagonals above or below the main diagonal
     should also be set to zero.

     The default value of K is zero, so that `triu' and `tril' normally
     include the main diagonal as part of the result matrix.

     If the value of K is negative, additional elements above (for
     `tril') or below (for `triu') the main diagonal are also selected.

     The absolute value of K must not be greater than the number of
     sub- or super-diagonals.

     For example,

          tril (ones (3), -1)
          =>  0  0  0
                   1  0  0
                   1  1  0

     and

          tril (ones (3), 1)
          =>  1  1  0
                   1  1  1
                   1  1  1

 -- Function File:  vec (X)
     Return the vector obtained by stacking the columns of the matrix X
     one above the other.

 -- Function File:  vech (X)
     Return the vector obtained by eliminating all supradiagonal
     elements of the square matrix X and stacking the result one column
     above the other.

 -- Function File:  prepad (X, L, C)
 -- Function File:  postpad (X, L, C)
 -- Function File:  postpad (X, L, C, DIM)
     Prepends (appends) the scalar value C to the vector X until it is
     of length L.  If the third argument is not supplied, a value of 0
     is used.

     If `length (X) > L', elements from the beginning (end) of X are
     removed until a vector of length L is obtained.

     If X is a matrix, elements are prepended or removed from each row.

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

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

   (1) For example, to first sort based on the values in column 1, and
then, for any values that are repeated in column 1, sort based on the
values found in column 2, etc.


File: octave.info,  Node: Special Utility Matrices,  Next: Famous Matrices,  Prev: Rearranging Matrices,  Up: Matrix Manipulation

18.3 Special Utility Matrices
=============================

 -- Built-in Function:  eye (X)
 -- Built-in Function:  eye (N, M)
 -- Built-in Function:  eye (..., CLASS)
     Return an identity matrix.  If invoked with a single scalar
     argument, `eye' returns a square matrix with the dimension
     specified.  If you supply two scalar arguments, `eye' takes them
     to be the number of rows and columns.  If given a vector with two
     elements, `eye' uses the values of the elements as the number of
     rows and columns, respectively.  For example,

          eye (3)
               =>  1  0  0
                   0  1  0
                   0  0  1

     The following expressions all produce the same result:

          eye (2)
          ==
          eye (2, 2)
          ==
          eye (size ([1, 2; 3, 4])

     The optional argument CLASS, allows `eye' to return an array of
     the specified type, like

          val = zeros (n,m, "uint8")

     For compatibility with MATLAB, calling `eye' with no arguments is
     equivalent to calling it with an argument of 1.

 -- Built-in Function:  ones (X)
 -- Built-in Function:  ones (N, M)
 -- Built-in Function:  ones (N, M, K, ...)
 -- Built-in Function:  ones (..., CLASS)
     Return a matrix or N-dimensional array whose elements are all 1.
     The arguments are handled the same as the arguments for `eye'.

     If you need to create a matrix whose values are all the same, you
     should use an expression like

          val_matrix = val * ones (n, m)

     The optional argument CLASS, allows `ones' to return an array of
     the specified type, like

          val = ones (n,m, "uint8")

 -- Built-in Function:  zeros (X)
 -- Built-in Function:  zeros (N, M)
 -- Built-in Function:  zeros (N, M, K, ...)
 -- Built-in Function:  zeros (..., CLASS)
     Return a matrix or N-dimensional array whose elements are all 0.
     The arguments are handled the same as the arguments for `eye'.

     The optional argument CLASS, allows `zeros' to return an array of
     the specified type, like

          val = zeros (n,m, "uint8")

 -- Function File:  repmat (A, M, N)
 -- Function File:  repmat (A, [M N])
     Form a block matrix of size M by N, with a copy of matrix A as
     each element.  If N is not specified, form an M by M block matrix.

 -- Loadable Function:  rand (X)
 -- Loadable Function:  rand (N, M)
 -- Loadable Function:  rand (`"seed"', X)
     Return a matrix with random elements uniformly distributed on the
     interval (0, 1).  The arguments are handled the same as the
     arguments for `eye'.  In addition, you can set the seed for the
     random number generator using the form

          rand ("seed", X)

     where X is a scalar value.  If called as

          rand ("seed")

     `rand' returns the current value of the seed.

 -- Loadable Function:  randn (X)
 -- Loadable Function:  randn (N, M)
 -- Loadable Function:  randn (`"seed"', X)
     Return a matrix with normally distributed random elements.  The
     arguments are handled the same as the arguments for `eye'.  In
     addition, you can set the seed for the random number generator
     using the form

          randn ("seed", X)

     where X is a scalar value.  If called as

          randn ("seed")

     `randn' returns the current value of the seed.

   The `rand' and `randn' functions use separate generators.  This
ensures that

     rand ("seed", 13);
     randn ("seed", 13);
     u = rand (100, 1);
     n = randn (100, 1);

and

     rand ("seed", 13);
     randn ("seed", 13);
     u = zeros (100, 1);
     n = zeros (100, 1);
     for i = 1:100
       u(i) = rand ();
       n(i) = randn ();
     end

produce equivalent results.

   Normally, `rand' and `randn' obtain their initial seeds from the
system clock, so that the sequence of random numbers is not the same
each time you run Octave.  If you really do need for to reproduce a
sequence of numbers exactly, you can set the seed to a specific value.

   If it is invoked without arguments, `rand' and `randn' return a
single element of a random sequence.

   The `rand' and `randn' functions use Fortran code from RANLIB, a
library of fortran routines for random number generation, compiled by
Barry W. Brown and James Lovato of the Department of Biomathematics at
The University of Texas, M.D. Anderson Cancer Center, Houston, TX 77030.

 -- Function File:  randperm (N)
     Return a row vector containing a random permutation of the
     integers from 1 to N.

 -- Built-in Function:  diag (V, K)
     Return a diagonal matrix with vector V on diagonal K.  The second
     argument is optional.  If it is positive, the vector is placed on
     the K-th super-diagonal.  If it is negative, it is placed on the
     -K-th sub-diagonal.  The default value of K is 0, and the vector
     is placed on the main diagonal.  For example,

          diag ([1, 2, 3], 1)
               =>  0  1  0  0
                   0  0  2  0
                   0  0  0  3
                   0  0  0  0

   The functions `linspace' and `logspace' make it very easy to create
vectors with evenly or logarithmically spaced elements.  *Note Ranges::.

 -- Built-in Function:  linspace (BASE, LIMIT, N)
     Return a row vector with N linearly spaced elements between BASE
     and LIMIT.  The number of elements, N, must be greater than 1.
     The BASE and LIMIT are always included in the range.  If BASE is
     greater than LIMIT, the elements are stored in decreasing order.
     If the number of points is not specified, a value of 100 is used.

     The `linspace' function always returns a row vector.

 -- Function File:  logspace (BASE, LIMIT, N)
     Similar to `linspace' except that the values are logarithmically
     spaced from 10^base to 10^limit.

     If LIMIT is equal to pi, the points are between 10^base and pi,
     _not_ 10^base and 10^pi, in order to  be compatible with the
     corresponding MATLAB function.

 -- Built-in Variable: warn_neg_dim_as_zero
     If the value of `warn_neg_dim_as_zero' is nonzero, print a warning
     for expressions like

          eye (-1)

     The default value is 0.

 -- Built-in Variable: warn_imag_to_real
     If the value of `warn_imag_to_real' is nonzero, a warning is
     printed for implicit conversions of complex numbers to real
     numbers.  The default value is 0.


File: octave.info,  Node: Famous Matrices,  Prev: Special Utility Matrices,  Up: Matrix Manipulation

18.4 Famous Matrices
====================

The following functions return famous matrix forms.

 -- Function File:  hankel (C, R)
     Return the Hankel matrix constructed given the first column C, and
     (optionally) the last row R.  If the last element of C is not the
     same as the first element of R, the last element of C is used.  If
     the second argument is omitted, it is assumed to be a vector of
     zeros with the same size as C.

     A Hankel matrix formed from an m-vector C, and an n-vector R, has
     the elements

          H(i,j) = c(i+j-1),  i+j-1 <= m;
          H(i,j) = r(i+j-m),  otherwise

 -- Function File:  hilb (N)
     Return the Hilbert matrix of order N.  The i, j element of a
     Hilbert matrix is defined as

          H (i, j) = 1 / (i + j - 1)

 -- Function File:  invhilb (N)
     Return the inverse of a Hilbert matrix of order N.  This can be
     computed computed exactly using

                      (i+j)         /n+i-1\  /n+j-1\   /i+j-2\ 2
           A(i,j) = -1      (i+j-1)(       )(       ) (       )
                                    \ n-j /  \ n-i /   \ i-2 /

                  = p(i) p(j) / (i+j-1)
     where
                       k  /k+n-1\   /n\
              p(k) = -1  (       ) (   )
                          \ k-1 /   \k/

     The validity of this formula can easily be checked by expanding
     the binomial coefficients in both formulas as factorials.  It can
     be derived more directly via the theory of Cauchy matrices: see J.
     W. Demmel, Applied Numerical Linear Algebra, page 92.

     Compare this with the numerical calculation of `inverse (hilb
     (n))', which suffers from the ill-conditioning of the Hilbert
     matrix, and the finite precision of your computer's floating point
     arithmetic.


 -- Function File:  sylvester_matrix (K)
     Return the Sylvester matrix of order n = 2^k.

 -- Function File:  toeplitz (C, R)
     Return the Toeplitz matrix constructed given the first column C,
     and (optionally) the first row R.  If the first element of C is
     not the same as the first element of R, the first element of C is
     used.  If the second argument is omitted, the first row is taken
     to be the same as the first column.

     A square Toeplitz matrix has the form:

          c(0)  r(1)   r(2)  ...  r(n)
          c(1)  c(0)   r(1)  ... r(n-1)
          c(2)  c(1)   c(0)  ... r(n-2)
           .     ,      ,   .      .
           .     ,      ,     .    .
           .     ,      ,       .  .
          c(n) c(n-1) c(n-2) ...  c(0)

 -- Function File:  vander (C)
     Return the Vandermonde matrix whose next to last column is C.

     A Vandermonde matrix has the form:

          c(1)^(n-1) ... c(1)^2  c(1)  1
          c(2)^(n-1) ... c(2)^2  c(2)  1
              .     .      .      .    .
              .       .    .      .    .
              .         .  .      .    .
          c(n)^(n-1) ... c(n)^2  c(n)  1


File: octave.info,  Node: Arithmetic,  Next: Linear Algebra,  Prev: Matrix Manipulation,  Up: Top

19 Arithmetic
*************

Unless otherwise noted, all of the functions described in this chapter
will work for real and complex scalar or matrix arguments.

* Menu:

* Utility Functions::
* Complex Arithmetic::
* Trigonometry::
* Sums and Products::
* Special Functions::
* Coordinate Transformations::
* Mathematical Constants::


File: octave.info,  Node: Utility Functions,  Next: Complex Arithmetic,  Up: Arithmetic

19.1 Utility Functions
======================

The following functions are available for working with complex numbers.
Each expects a single argument.  They are called "mapping functions"
because when given a matrix argument, they apply the given function to
each element of the matrix.

 -- Mapping Function:  ceil (X)
     Return the smallest integer not less than X.  If X is complex,
     return `ceil (real (X)) + ceil (imag (X)) * I'.

 -- Mapping Function:  exp (X)
     Compute the exponential of X.  To compute the matrix exponential,
     see *Note Linear Algebra::.

 -- Mapping Function:  fix (X)
     Truncate X toward zero.  If X is complex, return `fix (real (X)) +
     fix (imag (X)) * I'.

 -- Mapping Function:  floor (X)
     Return the largest integer not greater than X.  If X is complex,
     return `floor (real (X)) + floor (imag (X)) * I'.

 -- Loadable Function: G = gcd (A1, `...')
 -- Loadable Function: [G, V1, ...] = gcd (A1, `...')
     If a single argument is given then compute the greatest common
     divisor of the elements of this argument. Otherwise if more than
     one argument is given all arguments must be the same size or
     scalar. In this case the greatest common divisor is calculated for
     element individually. All elements must be integers. For example,

          gcd ([15, 20])
              =>  5

     and

          gcd ([15, 9], [20 18])
              =>  5  9

     Optional return arguments V1, etc, contain integer vectors such
     that,

          G = V1 .* A1 + V2 .* A2 + ...

     For backward compatiability with previous versions of this
     function, when all arguments are scalr, a single return argument
     V1 containing all of the values of V1, ... is acceptable.

 -- Mapping Function:  lcm (X, `...')
     Compute the least common multiple of the elements elements of X, or
     the list of all the arguments.  For example,

          lcm (a1, ..., ak)

     is the same as

          lcm ([a1, ..., ak]).

     All elements must be the same size or scalar.

 -- Mapping Function:  log (X)
     Compute the natural logarithm for each element of X.  To compute
     the matrix logarithm, see *Note Linear Algebra::.

 -- Mapping Function:  log10 (X)
     Compute the base-10 logarithm for each element of X.

 -- Mapping Function:  log2 (X)
 -- Mapping Function: [F, E] = log2 (X)
     Compute the base-2 logarithm of X.  With two outputs, returns F
     and E such that  1/2 <= abs(f) < 1 and x = f * 2^e.

 -- Mapping Function:  max (X, Y, DIM)
 -- Mapping Function: [W, IW] = max (X)
     For a vector argument, return the maximum value.  For a matrix
     argument, return the maximum value from each column, as a row
     vector, or over the dimension DIM if defined. For two matrices (or
     a matrix and scalar), return the pair-wise maximum.  Thus,

          max (max (X))

     returns the largest element of X, and

          max (2:5, pi)
              =>  3.1416  3.1416  4.0000  5.0000
     compares each element of the range `2:5' with `pi', and
     returns a row vector of the maximum values.

     For complex arguments, the magnitude of the elements are used for
     comparison.

     If called with one input and two output arguments, `max' also
     returns the first index of the maximum value(s). Thus,

          [x, ix] = max ([1, 3, 5, 2, 5])
              =>  x = 5
                  ix = 3

 -- Mapping Function:  min (X, Y, DIM)
 -- Mapping Function: [W, IW] = min (X)
     For a vector argument, return the minimum value.  For a matrix
     argument, return the minimum value from each column, as a row
     vector, or over the dimension DIM if defined. For two matrices (or
     a matrix and scalar), return the pair-wise minimum.  Thus,

          min (min (X))

     returns the smallest element of X, and

          min (2:5, pi)
              =>  2.0000  3.0000  3.1416  3.1416
     compares each element of the range `2:5' with `pi', and
     returns a row vector of the minimum values.

     For complex arguments, the magnitude of the elements are used for
     comparison.

     If called with one input and two output arguments, `min' also
     returns the first index of the minimum value(s). Thus,

          [x, ix] = min ([1, 3, 0, 2, 5])
              =>  x = 0
                  ix = 3

 -- Mapping Function:  mod (X, Y)
     Compute modulo function, using

          x - y .* floor (x ./ y)

     Note that this handles negative numbers correctly: `mod (-1, 3)'
     is 2, not -1 as `rem (-1, 3)' returns.  Also, `mod (X, 0)' returns
     X.

     An error message is printed if the dimensions of the arguments do
     not agree, or if either of the arguments is complex.

 -- Function File:  nextpow2 (X)
     If X is a scalar, returns the first integer N such that  2^n >=
     abs (x).

     If X is a vector, return `nextpow2 (length (X))'.

 -- Mapping Function:  pow2 (X)
 -- Mapping Function:  pow2 (F, E)
     With one argument, computes  2 .^ x for each element of X.  With
     two arguments, returns  f .* (2 .^ e).

 -- Mapping Function:  rem (X, Y)
     Return the remainder of `X / Y', computed using the expression

          x - y .* fix (x ./ y)

     An error message is printed if the dimensions of the arguments do
     not agree, or if either of the arguments is complex.

 -- Mapping Function:  round (X)
     Return the integer nearest to X.  If X is complex, return `round
     (real (X)) + round (imag (X)) * I'.

 -- Mapping Function:  sign (X)
     Compute the "signum" function, which is defined as

                     -1, x < 0;
          sign (x) =  0, x = 0;
                      1, x > 0.

     For complex arguments, `sign' returns `x ./ abs (X)'.

 -- Mapping Function:  sqrt (X)
     Compute the square root of X.  If X is negative, a complex result
     is returned.  To compute the matrix square root, see *Note Linear
     Algebra::.


File: octave.info,  Node: Complex Arithmetic,  Next: Trigonometry,  Prev: Utility Functions,  Up: Arithmetic

19.2 Complex Arithmetic
=======================

The following functions are available for working with complex numbers.
Each expects a single argument.  Given a matrix they work on an
element by element basis.  In the descriptions of the following
functions, Z is the complex number X + IY, where I is defined as `sqrt
(-1)'.

 -- Mapping Function:  abs (Z)
     Compute the magnitude of Z, defined as |Z| = `sqrt (x^2 + y^2)'.

     For example,

          abs (3 + 4i)
               => 5

 -- Mapping Function:  arg (Z)
 -- Mapping Function:  angle (Z)
     Compute the argument of Z, defined as THETA = `atan (Y/X)'.  in
     radians.

     For example,

          arg (3 + 4i)
               => 0.92730

 -- Mapping Function:  conj (Z)
     Return the complex conjugate of Z, defined as `conj (Z)' = X - IY.

 -- Mapping Function:  imag (Z)
     Return the imaginary part of Z as a real number.

 -- Mapping Function:  real (Z)
     Return the real part of Z.


File: octave.info,  Node: Trigonometry,  Next: Sums and Products,  Prev: Complex Arithmetic,  Up: Arithmetic

19.3 Trigonometry
=================

Octave provides the following trigonometric functions.  Angles are
specified in radians.  To convert from degrees to radians multipy by
`pi/180'  (e.g. `sin (30 * pi/180)' returns the sine of 30 degrees).

 -- Mapping Function:  sin (X)
     Compute the sine of each element of X.

 -- Mapping Function:  cos (X)
     Compute the cosine of each element of X.

 -- Mapping Function:  tan (Z)
     Compute tangent of each element of X.

 -- Mapping Function:  sec (X)
     Compute the secant of each element of X.

 -- Mapping Function:  csc (X)
     Compute the cosecant of each element of X.

 -- Mapping Function:  cot (X)
     Compute the cotangent of each element of X.

 -- Mapping Function:  asin (X)
     Compute the inverse sine of each element of X.

 -- Mapping Function:  acos (X)
     Compute the inverse cosine of each element of X.

 -- Mapping Function:  atan (X)
     Compute the inverse tangent of each element of X.

 -- Mapping Function:  asec (X)
     Compute the inverse secant of each element of X.

 -- Mapping Function:  acsc (X)
     Compute the inverse cosecant of each element of X.

 -- Mapping Function:  acot (X)
     Compute the inverse cotangent of each element of X.

 -- Mapping Function:  sinh (X)
     Compute the inverse hyperbolic sine of each element of X.

 -- Mapping Function:  cosh (X)
     Compute the hyperbolic cosine of each element of X.

 -- Mapping Function:  tanh (X)
     Compute hyperbolic tangent of each element of X.

 -- Mapping Function:  sech (X)
     Compute the hyperbolic secant of each element of X.

 -- Mapping Function:  csch (X)
     Compute the hyperbolic cosecant of each element of X.

 -- Mapping Function:  coth (X)
     Compute the hyperbolic cotangent of each element of X.

 -- Mapping Function:  asinh (X)
     Compute the inverse hyperbolic sine of each element of X.

 -- Mapping Function:  acosh (X)
     Compute the inverse hyperbolic cosine of each element of X.

 -- Mapping Function:  atanh (X)
     Compute the inverse hyperbolic tangent of each element of X.

 -- Mapping Function:  asech (X)
     Compute the inverse hyperbolic secant of each element of X.

 -- Mapping Function:  acsch (X)
     Compute the inverse hyperbolic cosecant of each element of X.

 -- Mapping Function:  acoth (X)
     Compute the inverse hyperbolic cotangent of each element of X.

   Each of these functions expect a single argument.  For matrix
arguments, they work on an element by element basis.  For example,

     sin ([1, 2; 3, 4])
          =>  0.84147   0.90930
              0.14112  -0.75680

 -- Mapping Function:  atan2 (Y, X)
     Compute atan (Y / X) for corresponding elements of Y and X.  The
     result is in range -pi to pi.


File: octave.info,  Node: Sums and Products,  Next: Special Functions,  Prev: Trigonometry,  Up: Arithmetic

19.4 Sums and Products
======================

 -- Built-in Function:  sum (X, DIM)
     Sum of elements along dimension DIM.  If DIM is omitted, it
     defaults to 1 (column-wise sum).

     As a special case, if X is a vector and DIM is omitted, return the
     sum of the elements.

 -- Built-in Function:  prod (X, DIM)
     Product of elements along dimension DIM.  If DIM is omitted, it
     defaults to 1 (column-wise products).

     As a special case, if X is a vector and DIM is omitted, return the
     product of the elements.

 -- Built-in Function:  cumsum (X, DIM)
     Cumulative sum of elements along dimension DIM.  If DIM is
     omitted, it defaults to 1 (column-wise cumulative sums).

     As a special case, if X is a vector and DIM is omitted, return the
     cumulative sum of the elements as a vector with the same
     orientation as X.

 -- Built-in Function:  cumprod (X, DIM)
     Cumulative product of elements along dimension DIM.  If DIM is
     omitted, it defaults to 1 (column-wise cumulative products).

     As a special case, if X is a vector and DIM is omitted, return the
     cumulative product of the elements as a vector with the same
     orientation as X.

 -- Built-in Function:  sumsq (X, DIM)
     Sum of squares of elements along dimension DIM.  If DIM is
     omitted, it defaults to 1 (column-wise sum of squares).

     As a special case, if X is a vector and DIM is omitted, return the
     sum of squares of the elements.

     This function is conceptually equivalent to computing
          sum (x .* conj (x), dim)
     but it uses less memory and avoids calling conj if X is real.


File: octave.info,  Node: Special Functions,  Next: Coordinate Transformations,  Prev: Sums and Products,  Up: Arithmetic

19.5 Special Functions
======================

 -- Loadable Function: [J, IERR] = besselj (ALPHA, X, OPT)
 -- Loadable Function: [Y, IERR] = bessely (ALPHA, X, OPT)
 -- Loadable Function: [I, IERR] = besseli (ALPHA, X, OPT)
 -- Loadable Function: [K, IERR] = besselk (ALPHA, X, OPT)
 -- Loadable Function: [H, IERR] = besselh (ALPHA, K, X, OPT)
     Compute Bessel or Hankel functions of various kinds:

    `besselj'
          Bessel functions of the first kind.

    `bessely'
          Bessel functions of the second kind.

    `besseli'
          Modified Bessel functions of the first kind.

    `besselk'
          Modified Bessel functions of the second kind.

    `besselh'
          Compute Hankel functions of the first (K = 1) or second (K  =
          2) kind.

     If the argument OPT is supplied, the result is scaled by the `exp
     (-I*X)' for K = 1 or `exp (I*X)' for  K = 2.

     If ALPHA is a scalar, the result is the same size as X.  If X is a
     scalar, the result is the same size as ALPHA.  If ALPHA is a row
     vector and X is a column vector, the result is a matrix with
     `length (X)' rows and `length (ALPHA)' columns.  Otherwise, ALPHA
     and X must conform and the result will be the same size.

     The value of ALPHA must be real.  The value of X may be complex.

     If requested, IERR contains the following status information and
     is the same size as the result.

       0. Normal return.

       1. Input error, return `NaN'.

       2. Overflow, return `Inf'.

       3. Loss of significance by argument reduction results in less
          than half of machine accuracy.

       4. Complete loss of significance by argument reduction, return
          `NaN'.

       5. Error--no computation, algorithm termination condition not
          met, return `NaN'.

 -- Loadable Function: [A, IERR] = airy (K, Z, OPT)
     Compute Airy functions of the first and second kind, and their
     derivatives.

            K   Function   Scale factor (if a third argument is supplied)
           ---  --------   ----------------------------------------------
            0   Ai (Z)     exp ((2/3) * Z * sqrt (Z))
            1   dAi(Z)/dZ  exp ((2/3) * Z * sqrt (Z))
            2   Bi (Z)     exp (-abs (real ((2/3) * Z *sqrt (Z))))
            3   dBi(Z)/dZ  exp (-abs (real ((2/3) * Z *sqrt (Z))))

     The function call `airy (Z)' is equivalent to `airy (0, Z)'.

     The result is the same size as Z.

     If requested, IERR contains the following status information and
     is the same size as the result.

       0. Normal return.

       1. Input error, return `NaN'.

       2. Overflow, return `Inf'.

       3. Loss of significance by argument reduction results in less
          than half  of machine accuracy.

       4. Complete loss of significance by argument reduction, return
          `NaN'.

       5. Error--no computation, algorithm termination condition not
          met, return `NaN'

 -- Mapping Function:  beta (A, B)
     Return the Beta function,

          beta (a, b) = gamma (a) * gamma (b) / gamma (a + b).

 -- Mapping Function:  betainc (X, A, B)
     Return the incomplete Beta function,

                                              x
                                             /
          betai (a, b, x) = beta (a, b)^(-1) | t^(a-1) (1-t)^(b-1) dt.
                                             /
                                          t=0

     If x has more than one component, both A and B must be scalars.
     If X is a scalar, A and B must be of compatible dimensions.

 -- Mapping Function:  bincoeff (N, K)
     Return the binomial coefficient of N and K, defined as

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

     For example,

          bincoeff (5, 2)
          => 10

 -- Mapping Function:  erf (Z)
     Computes the error function,

                                   z
                                  /
          erf (z) = (2/sqrt (pi)) | e^(-t^2) dt
                                  /
                               t=0

 -- Mapping Function:  erfc (Z)
     Computes the complementary error function, `1 - erf (Z)'.

 -- Mapping Function:  erfinv (Z)
     Computes the inverse of the error function.

 -- Mapping Function:  gamma (Z)
     Computes the Gamma function,

                      infinity
                      /
          gamma (z) = | t^(z-1) exp (-t) dt.
                      /
                   t=0

 -- Mapping Function:  gammainc (X, A)
     Computes the incomplete gamma function,

                                          x
                                1        /
          gammainc (x, a) = ---------    | exp (-t) t^(a-1) dt
                            gamma (a)    /
                                      t=0

     If A is scalar, then `gammainc (X, A)' is returned for each
     element of X and vice versa.

     If neither X nor A is scalar, the sizes of X and A must agree, and
     GAMMAINC is applied element-by-element.

 -- Mapping Function:  lgamma (A, X)
 -- Mapping Function:  gammaln (A, X)
     Return the natural logarithm of the gamma function.

 -- Function File:  cross (X, Y, DIM)
     Computes the vector cross product of the two 3-dimensional vectors
     X and Y.

          cross ([1,1,0], [0,1,1])
          => [ 1; -1; 1 ]

     If X and Y are matrices, the cross product is applied along the
     first dimension with 3 elements. The optional argument DIM is used
     to force the cross product to be calculated along the dimension
     defiend by DIM.

 -- Function File:  commutation_matrix (M, N)
     Return the commutation matrix  K(m,n)  which is the unique M*N by
     M*N  matrix such that K(m,n) * vec(A) = vec(A')  for all m by n
     matrices A.

     If only one argument M is given, K(m,m)  is returned.

     See Magnus and Neudecker (1988), Matrix differential calculus with
     applications in statistics and econometrics.

 -- Function File:  duplication_matrix (N)
     Return the duplication matrix Dn  which is the unique n^2 by
     n*(n+1)/2  matrix such that Dn vech (A) = vec (A)  for all
     symmetric n by n  matrices A.

     See Magnus and Neudecker (1988), Matrix differential calculus with
     applications in statistics and econometrics.


File: octave.info,  Node: Coordinate Transformations,  Next: Mathematical Constants,  Prev: Special Functions,  Up: Arithmetic

19.6 Coordinate Transformations
===============================

 -- Function File:  [THETA, R] = cart2pol (X, Y)
 -- Function File:  [THETA, R, Z] = cart2pol (X, Y, Z)
     Transform cartesian to polar or cylindrical coordinates.  X, Y
     (and Z) must be of same shape.  THETA describes the angle relative
     to the x - axis.  R is the distance to the z - axis (0, 0, z).

 -- Function File:  [X, Y] = pol2cart (THETA, R)
 -- Function File:  [X, Y, Z] = pol2cart (THETA, R, Z)
     Transform polar or cylindrical to cartesian coordinates.  THETA, R
     (and Z) must be of same shape.  THETA describes the angle relative
     to the x - axis.  R is the distance to the z - axis (0, 0, z).

 -- Function File:  [THETA, PHI, R] = cart2sph (X, Y, Z)
     Transform cartesian to spherical coordinates.  X, Y and Z must be
     of same shape.  THETA describes the angle relative to the x - axis.
     PHI is the angle relative to the xy - plane.  R is the distance to
     the origin (0, 0, 0).

 -- Function File:  [X, Y, Z] = sph2cart (THETA, PHI, R)
     Transform spherical to cartesian coordinates.  X, Y and Z must be
     of same shape.  THETA describes the angle relative to the x-axis.
     PHI is the angle relative to the xy-plane.  R is the distance to
     the origin (0, 0, 0).


File: octave.info,  Node: Mathematical Constants,  Prev: Coordinate Transformations,  Up: Arithmetic

19.7 Mathematical Constants
===========================

 -- Built-in Constant: I
 -- Built-in Constant: J
 -- Built-in Constant: i
 -- Built-in Constant: j
     A pure imaginary number, defined as   `sqrt (-1)'.  These built-in
     variables behave like functions so you can use the names for other
     purposes.  If you use them as variables and assign values to them
     and then clear them, they once again assume their special
     predefined values *Note Status of Variables::.

 -- Built-in Constant: Inf
 -- Built-in Constant: inf
     Infinity.  This is the result of an operation like 1/0, or an
     operation that results in a floating point overflow.

 -- Built-in Constant: NaN
 -- Built-in Constant: nan
     Not a number.  This is the result of an operation like 0/0, or
     `Inf - Inf', or any operation with a NaN.

     Note that NaN always compares not equal to NaN.  This behavior is
     specified by the IEEE standard for floating point arithmetic.  To
     find NaN values, you must use the `isnan' function.

 -- Built-in Constant: pi
     The ratio of the circumference of a circle to its diameter.
     Internally, `pi' is computed as `4.0 * atan (1.0)'.

 -- Built-in Constant: e
     The base of natural logarithms.  The constant  E  satisfies the
     equation  `log' (E) = 1.

 -- Built-in Constant: eps
     The machine precision.  More precisely, `eps' is the largest
     relative spacing between any two adjacent numbers in the machine's
     floating point system.  This number is obviously system-dependent.
     On machines that support 64 bit IEEE floating point arithmetic,
     `eps' is approximately  2.2204e-16.

 -- Built-in Constant: realmax
     The largest floating point number that is representable.  The
     actual value is system-dependent.  On machines that support 64-bit
     IEEE floating point arithmetic, `realmax' is approximately
     1.7977e+308

 -- Built-in Constant: realmin
     The smallest normalized floating point number that is
     representable.  The actual value is system-dependent.  On machines
     that support 64-bit IEEE floating point arithmetic, `realmin' is
     approximately  2.2251e-308



File: octave.info,  Node: Linear Algebra,  Next: Nonlinear Equations,  Prev: Arithmetic,  Up: Top

20 Linear Algebra
*****************

This chapter documents the linear algebra functions of Octave.
Reference material for many of these functions may be found in Golub
and Van Loan, `Matrix Computations, 2nd Ed.', Johns Hopkins, 1989, and
in `LAPACK Users' Guide', SIAM, 1992.

* Menu:

* Basic Matrix Functions::
* Matrix Factorizations::
* Functions of a Matrix::


File: octave.info,  Node: Basic Matrix Functions,  Next: Matrix Factorizations,  Up: Linear Algebra

20.1 Basic Matrix Functions
===========================

 -- Loadable Function: AA = balance (A, OPT)
 -- Loadable Function: [DD, AA] = balance (A, OPT)
 -- Loadable Function: [CC, DD, AA, BB] = balance (A, B, OPT)
     `[dd, aa] = balance (a)' returns `aa = dd \ a * dd'.  `aa' is a
     matrix whose row and column norms are roughly equal in magnitude,
     and `dd' = `p * d', where `p' is a permutation matrix and `d' is a
     diagonal matrix of powers of two.  This allows the equilibration
     to be computed without roundoff.  Results of eigenvalue
     calculation are typically improved by balancing first.

     `[cc, dd, aa, bb] = balance (a, b)' returns `aa = cc*a*dd' and `bb
     = cc*b*dd)', where `aa' and `bb' have non-zero elements of
     approximately the same magnitude and `cc' and `dd' are permuted
     diagonal matrices as in `dd' for the algebraic eigenvalue problem.

     The eigenvalue balancing option `opt' is selected as follows:

    `"N"', `"n"'
          No balancing; arguments copied, transformation(s) set to
          identity.

    `"P"', `"p"'
          Permute argument(s) to isolate eigenvalues where possible.

    `"S"', `"s"'
          Scale to improve accuracy of computed eigenvalues.

    `"B"', `"b"'
          Permute and scale, in that order. Rows/columns of a (and b)
          that are isolated by permutation are not scaled.  This is the
          default behavior.

     Algebraic eigenvalue balancing uses standard LAPACK routines.

     Generalized eigenvalue problem balancing uses Ward's algorithm
     (SIAM Journal on Scientific and Statistical Computing, 1981).

 -- Function File:  cond (A)
     Compute the (two-norm) condition number of a matrix. `cond (a)' is
     defined as `norm (a) * norm (inv (a))', and is computed via a
     singular value decomposition.

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

 -- Function File:  dmult (A, B)
     If A is a vector of length `rows (B)', return `diag (A) * B' (but
     computed much more efficiently).

 -- Function File:  dot (X, Y, DIM)
     Computes the dot product of two vectors. If X and Y are matrices,
     calculate the dot-product along the first non-singleton dimension.
     If the optional argument DIM is given, calculate the dot-product
     along this dimension.

 -- Loadable Function: LAMBDA = eig (A)
 -- Loadable Function: [V, LAMBDA] = eig (A)
     The eigenvalues (and eigenvectors) of a matrix are computed in a
     several step process which begins with a Hessenberg decomposition,
     followed by a Schur decomposition, from which the eigenvalues are
     apparent.  The eigenvectors, when desired, are computed by further
     manipulations of the Schur decomposition.

 -- Loadable Function: G = givens (X, Y)
 -- Loadable Function: [C, S] = givens (X, Y)
     Return a 2 by 2 orthogonal matrix `G = [C S; -S' C]' such that `G
     [X; Y] = [*; 0]' with X and Y scalars.

     For example,

          givens (1, 1)
               =>   0.70711   0.70711
                   -0.70711   0.70711

 -- Loadable Function: [X, RCOND] =  inv (A)
 -- Loadable Function: [X, RCOND] =  inverse (A)
     Compute the inverse of the square matrix A.  Return an estimate of
     the reciprocal condition number if requested, otherwise warn of an
     ill-conditioned matrix if the reciprocal condition number is small.

 -- Function File:  norm (A, P)
     Compute the p-norm of the matrix A.  If the second argument is
     missing, `p = 2' is assumed.

     If A is a matrix:

    P = `1'
          1-norm, the largest column sum of the absolute values of A.

    P = `2'
          Largest singular value of A.

    P = `Inf'
          Infinity norm, the largest row sum of the absolute values of
          A.

    P = `"fro"'
          Frobenius norm of A, `sqrt (sum (diag (A' * A)))'.

     If A is a vector or a scalar:

    P = `Inf'
          `max (abs (A))'.

    P = `-Inf'
          `min (abs (A))'.

    other
          p-norm of A, `(sum (abs (A) .^ P)) ^ (1/P)'.

 -- Function File:  null (A, TOL)
     Return an orthonormal basis of the null space of A.

     The dimension of the null space is taken as the number of singular
     values of A not greater than TOL.  If the argument TOL is missing,
     it is computed as

          max (size (A)) * max (svd (A)) * eps

 -- Function File:  orth (A, TOL)
     Return an orthonormal basis of the range space of A.

     The dimension of the range space is taken as the number of singular
     values of A greater than TOL.  If the argument TOL is missing, it
     is computed as

          max (size (A)) * max (svd (A)) * eps

 -- Loadable Function:  pinv (X, TOL)
     Return the pseudoinverse of X.  Singular values less than TOL are
     ignored.

     If the second argument is omitted, it is assumed that

          tol = max (size (X)) * sigma_max (X) * eps,

     where `sigma_max (X)' is the maximal singular value of X.

 -- Function File:  rank (A, TOL)
     Compute the rank of A, using the singular value decomposition.
     The rank is taken to be the number  of singular values of A that
     are greater than the specified tolerance TOL.  If the second
     argument is omitted, it is taken to be

          tol = max (size (A)) * sigma(1) * eps;

     where `eps' is machine precision and `sigma(1)' is the largest
     singular value of A.

 -- Function File:  trace (A)
     Compute the trace of A, `sum (diag (A))'.


File: octave.info,  Node: Matrix Factorizations,  Next: Functions of a Matrix,  Prev: Basic Matrix Functions,  Up: Linear Algebra

20.2 Matrix Factorizations
==========================

 -- Loadable Function:  chol (A)
     Compute the Cholesky factor, R, of the symmetric positive definite
     matrix A, where

          r' * r = a.


 -- Loadable Function: H = hess (A)
 -- Loadable Function: [P, H] = hess (A)
     Compute the Hessenberg decomposition of the matrix A.

     The Hessenberg decomposition is usually used as the first step in
     an eigenvalue computation, but has other applications as well (see
     Golub, Nash, and Van Loan, IEEE Transactions on Automatic Control,
     1979).  The Hessenberg decomposition is `p * h * p' = a' where `p'
     is a square unitary matrix (`p' * p = I', using complex-conjugate
     transposition) and `h' is upper Hessenberg (`i >= j+1 => h (i, j)
     = 0').

 -- Loadable Function: [L, U, P] = lu (A)
     Compute the LU decomposition of A, using subroutines from LAPACK.
     The result is returned in a permuted form, according to the
     optional return value P.  For example, given the matrix `a = [1,
     2; 3, 4]',

          [l, u, p] = lu (a)

     returns

          l =

            1.00000  0.00000
            0.33333  1.00000

          u =

            3.00000  4.00000
            0.00000  0.66667

          p =

            0  1
            1  0

     The matrix is not required to be square..

 -- Loadable Function: [Q, R, P] = qr (A)
     Compute the QR factorization of A, using standard LAPACK
     subroutines.  For example, given the matrix `a = [1, 2; 3, 4]',

          [q, r] = qr (a)

     returns

          q =

            -0.31623  -0.94868
            -0.94868   0.31623

          r =

            -3.16228  -4.42719
             0.00000  -0.63246

     The `qr' factorization has applications in the solution of least
     squares problems

          `min norm(A x - b)'

     for overdetermined systems of equations (i.e., `a'  is a tall,
     thin matrix).  The QR factorization is `q * r = a' where `q' is an
     orthogonal matrix and `r' is upper triangular.

     The permuted QR factorization `[Q, R, P] = qr (A)' forms the QR
     factorization such that the diagonal entries of `r' are decreasing
     in magnitude order.  For example, given the matrix `a = [1, 2; 3,
     4]',

          [q, r, p] = qr(a)

     returns

          q =

            -0.44721  -0.89443
            -0.89443   0.44721

          r =

            -4.47214  -3.13050
             0.00000   0.44721

          p =

             0  1
             1  0

     The permuted `qr' factorization `[q, r, p] = qr (a)' factorization
     allows the construction of an orthogonal basis of `span (a)'.

 -- Loadable Function: LAMBDA = qz (A, B)
     Generalized eigenvalue problem A x = s B x, QZ decomposition.
     There are three ways to call this function:
       1. `lambda = qz(A,B)'

          Computes the generalized eigenvalues LAMBDA of (A - s B).

       2. `[AA, BB, Q, Z, V, W, lambda] = qz (A, B)'

          Computes qz decomposition, generalized eigenvectors, and
            generalized eigenvalues of (A - sB)
                       A*V = B*V*diag(lambda)
                       W'*A = diag(lambda)*W'*B
                       AA = Q'*A*Z, BB = Q'*B*Z
          with Q and Z orthogonal (unitary)= I

       3. `[AA,BB,Z{, lambda}] = qz(A,B,opt)'

          As in form [2], but allows ordering of generalized eigenpairs
                 for (e.g.) solution of discrete time algebraic
          Riccati equations.          Form 3 is not available for
          complex matrices, and does not compute         the
          generalized eigenvectors V, W, nor the orthogonal matrix Q.
         OPT
               for ordering eigenvalues of the GEP pencil.  The leading
               block              of the revised pencil contains all
               eigenvalues that satisfy:
              `"N"'
                    = unordered (default)

              `"S"'
                    = small: leading block has all |lambda| <=1

              `"B"'
                    = big: leading block has all |lambda >= 1

              `"-"'
                    = negative real part: leading  block has all
                    eigenvalues                   in the open left
                    half-plant

              `"+"'
                    = nonnegative real part:  leading block has all
                    eigenvalues                   in the closed right
                    half-plane

     Note: qz performs permutation balancing, but not scaling (see
     balance).        Order of output arguments was selected for
     compatibility with MATLAB


 -- Function File: [AA, BB, Q, Z] = qzhess (A, B)
     Compute the Hessenberg-triangular decomposition of the matrix
     pencil `(A, B)', returning `AA = Q * A * Z', `BB = Q * B * Z',
     with Q and Z orthogonal.  For example,

          [aa, bb, q, z] = qzhess ([1, 2; 3, 4], [5, 6; 7, 8])
          => aa = [ -3.02244, -4.41741;  0.92998,  0.69749 ]
          => bb = [ -8.60233, -9.99730;  0.00000, -0.23250 ]
          =>  q = [ -0.58124, -0.81373; -0.81373,  0.58124 ]
          =>  z = [ 1, 0; 0, 1 ]

     The Hessenberg-triangular decomposition is the first step in Moler
     and Stewart's QZ decomposition algorithm.

     Algorithm taken from Golub and Van Loan, `Matrix Computations, 2nd
     edition'.

 -- Loadable Function: S = schur (A)
 -- Loadable Function: [U, S] = schur (A, OPT)
     The Schur decomposition is used to compute eigenvalues of a square
     matrix, and has applications in the solution of algebraic Riccati
     equations in control (see `are' and `dare').  `schur' always
     returns `s = u' * a * u' where `u'  is a unitary matrix (`u'* u'
     is identity) and `s' is upper triangular.  The eigenvalues of `a'
     (and `s') are the diagonal elements of `s' If the matrix `a' is
     real, then the real Schur decomposition is computed, in which the
     matrix `u' is orthogonal and `s' is block upper triangular with
     blocks of size at most `2 x 2' along the diagonal.  The diagonal
     elements of `s' (or the eigenvalues of the `2 x 2' blocks, when
     appropriate) are the eigenvalues of `a' and `s'.

     The eigenvalues are optionally ordered along the diagonal
     according to the value of `opt'.  `opt = "a"' indicates that all
     eigenvalues with negative real parts should be moved to the leading
     block of `s' (used in `are'), `opt = "d"' indicates that all
     eigenvalues with magnitude less than one should be moved to the
     leading block of `s' (used in `dare'), and `opt = "u"', the
     default, indicates that no ordering of eigenvalues should occur.
     The leading `k' columns of `u' always span the `a'-invariant
     subspace corresponding to the `k' leading eigenvalues of `s'.

 -- Loadable Function: S = svd (A)
 -- Loadable Function: [U, S, V] = svd (A)
     Compute the singular value decomposition of A

          a = u * sigma * v'

     The function `svd' normally returns the vector of singular values.
     If asked for three return values, it computes U, S, and V.  For
     example,

          svd (hilb (3))

     returns

          ans =

            1.4083189
            0.1223271
            0.0026873

     and

          [u, s, v] = svd (hilb (3))

     returns

          u =

            -0.82704   0.54745   0.12766
            -0.45986  -0.52829  -0.71375
            -0.32330  -0.64901   0.68867

          s =

            1.40832  0.00000  0.00000
            0.00000  0.12233  0.00000
            0.00000  0.00000  0.00269

          v =

            -0.82704   0.54745   0.12766
            -0.45986  -0.52829  -0.71375
            -0.32330  -0.64901   0.68867

     If given a second argument, `svd' returns an economy-sized
     decomposition, eliminating the unnecessary rows or columns of U or
     V.

 -- Function File: [HOUSV, BETA, ZER] = housh (X, J, Z)
     Computes householder reflection vector housv to reflect x to be
     jth column of identity, i.e., (I - beta*housv*housv')x =e(j) inputs
      x: vector   j: index into vector   z: threshold for zero
     (usually should be the number 0) outputs: (see Golub and Van Loan)
      beta: If beta = 0, then no reflection need be applied (zer set
     to 0)   housv: householder vector

 -- Function File: [U, H, NU] = krylov (A, V, K, EPS1, PFLG);
     construct orthogonal basis U of block Krylov subspace;  [v a*v
     a^2*v ... a^(k+1)*v]; method used: householder reflections to
     guard against loss of orthogonality eps1: threshhold for 0
     (default: 1e-12) pflg: flag to use row pivoting  (improves
     numerical behavior)   0 [default]: no pivoting; prints a warning
     message if trivial                null space is corrupted   1
        : pivoting performed

     outputs:   u: orthogonal basis of block krylov subspace   h:
     Hessenberg matrix; if v is a vector then a u = u h      otherwise
     h is meaningless  nu: dimension of span of krylov subspace (based
     on eps1) if b is a vector and k > m-1, krylov returns h = the
     Hessenberg decompostion of a.

     Reference: Hodel and Misra, "Partial Pivoting in the Computation of
        Krylov Subspaces", to be submitted to Linear Algebra and its
      Applications


File: octave.info,  Node: Functions of a Matrix,  Prev: Matrix Factorizations,  Up: Linear Algebra

20.3 Functions of a Matrix
==========================

 -- Loadable Function:  expm (A)
     Return the exponential of a matrix, defined as the infinite Taylor
     series

          expm(a) = I + a + a^2/2! + a^3/3! + ...

     The Taylor series is _not_ the way to compute the matrix
     exponential; see Moler and Van Loan, `Nineteen Dubious Ways to
     Compute the Exponential of a Matrix', SIAM Review, 1978.  This
     routine uses Ward's diagonal Pade' approximation method with three
     step preconditioning (SIAM Journal on Numerical Analysis, 1977).
     Diagonal Pade'  approximations are rational polynomials of matrices

               -1
          D (a)   N (a)

     whose Taylor series matches the first `2q+1' terms of the Taylor
     series above; direct evaluation of the Taylor series (with the
     same preconditioning steps) may be desirable in lieu of the Pade'
     approximation when `Dq(a)' is ill-conditioned.

 -- Function File:  logm (A)
     Compute the matrix logarithm of the square matrix A.  Note that
     this is currently implemented in terms of an eigenvalue expansion
     and needs to be improved to be more robust.

 -- Loadable Function: [RESULT, ERROR_ESTIMATE] = sqrtm (A)
     Compute the matrix square root of the square matrix A.

     Ref: Nicholas J. Higham. A new sqrtm for MATLAB. Numerical Analysis
     Report No. 336, Manchester Centre for Computational Mathematics,
     Manchester, England, January 1999.

 -- Function File:  kron (A, B)
     Form the kronecker product of two matrices, defined block by block
     as

          x = [a(i, j) b]

     For example,

          kron (1:4, ones (3, 1))
                =>  1  2  3  4
                    1  2  3  4
                    1  2  3  4

 -- Loadable Function: X = syl (A, B, C)
     Solve the Sylvester equation

          A X + X B + C = 0
     using standard LAPACK subroutines.  For example,

          syl ([1, 2; 3, 4], [5, 6; 7, 8], [9, 10; 11, 12])
               => [ -0.50000, -0.66667; -0.66667, -0.50000 ]


File: octave.info,  Node: Nonlinear Equations,  Next: Sparse Matrices,  Prev: Linear Algebra,  Up: Top

21 Nonlinear Equations
**********************

Octave can solve sets of nonlinear equations of the form

     F (x) = 0

using the function `fsolve', which is based on the MINPACK subroutine
`hybrd'.

 -- Loadable Function: [X, INFO, MSG] = fsolve (FCN, X0)
     Given FCN, the name of a function of the form `f (X)' and an
     initial starting point X0, `fsolve' solves the set of equations
     such that `f(X) == 0'.

     If FCN is a two-element string array, the first element names the
     function f described above, and the second element names a
     function of the form `j (X)' to compute the Jacobian matrix with
     elements

                     df_i
          jac(i,j) = ----
                     dx_j

     You can use the function `fsolve_options' to set optional
     parameters for `fsolve'.

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

     Options include

    `"tolerance"'
          Nonnegative relative tolerance.

   Here is a complete example.  To solve the set of equations

     -2x^2 + 3xy   + 4 sin(y) = 6
      3x^2 - 2xy^2 + 3 cos(x) = -4

you first need to write a function to compute the value of the given
function.  For example:

     function y = f (x)
       y(1) = -2*x(1)^2 + 3*x(1)*x(2)   + 4*sin(x(2)) - 6;
       y(2) =  3*x(1)^2 - 2*x(1)*x(2)^2 + 3*cos(x(1)) + 4;
     endfunction

   Then, call `fsolve' with a specified initial condition to find the
roots of the system of equations.  For example, given the function `f'
defined above,

     [x, info] = fsolve ("f", [1; 2])

results in the solution

     x =

       0.57983
       2.54621

     info = 1

   A value of `info = 1' indicates that the solution has converged.

   The function `perror' may be used to print English messages
corresponding to the numeric error codes.  For example,

     perror ("fsolve", 1)
          -| solution converged to requested tolerance


File: octave.info,  Node: Sparse Matrices,  Next: Quadrature,  Prev: Nonlinear Equations,  Up: Top

22 Sparse Matrices
******************

* Menu:

* Basics:: The Creation and Manipulation of Sparse Matrices
* Graph Theory:: Graphs are their use with Sparse Matrices
* Sparse Linear Algebra:: Linear Algebra on Sparse Matrices
* Iterative Techniques:: Iterative Techniques applied to Sparse Matrices
* Oct-Files:: Using Sparse Matrices in Oct-files
* License:: Licensing of Third Party Software
* Function Reference:: Documentation from the Specific Sparse Functions


File: octave.info,  Node: Basics,  Next: Graph Theory,  Prev: Sparse Matrices,  Up: Sparse Matrices

22.1 The Creation and Manipulation of Sparse Matrices
=====================================================

The size of mathematical problems that can be treated at any particular
time is generally limited by the available computing resources. Both,
the speed of the computer and its available memory place limitation on
the problem size.

   There are many classes mathematical problems which give rise to
matrices, where a large number of the elements are zero. In this case
it makes sense to have a special matrix type to handle this class of
problems where only the non-zero elements of the matrix are stored. Not
only done this reduce the amount of memory to store the matrix, but it
also means that operations on this type of matrix can take advantage of
the a-priori knowledge of the positions of the non-zero elements to
accelerate their calculations.

   A matrix type that stores only the non-zero elements is generally
called sparse. It is the purpose of this document to discuss the basics
of the storage and creation of sparse matrices and the fundamental
operations on them.

   THIS DOCUMENT STILL HAS LARGE BLANKS. PLEASE FILL THEM IN. LOOK FOR
THE TAG "WRITE ME"

* Menu:

* Storage:: Storage of Sparse Matrices
* Creation:: Creating Sparse Matrices
* Operators and Functions:: Basic Operators and Functions on Sparse Matrices
* Information:: Finding out Information about Sparse Matrices


File: octave.info,  Node: Storage,  Next: Creation,  Prev: Basics,  Up: Basics

22.1.1 Storage of Sparse Matrices
---------------------------------

It is not strictly speaking necessary for the user to understand how
sparse matrices are stored. However, such an understanding will help to
get an understanding of the size of sparse matrices. Understanding the
storage technique is also necessary for those users wishing to create
their own oct-files.

   There are many different means of storing sparse matrix data. What
all of the methods have in common is that they attempt to reduce the
compelxity and storage given a-priori knowledge of the particular class
of problems that will be solved. A good summary of the available
techniques for storing sparse matrix is given by Saad (1).  With full
matrices, knowledge of the point of an element of the matrix within the
matrix is implied by its position in the computers memory.  However,
this is not the case for sparse matrices, and so the positions of the
non-zero elements of the matrix must equally be stored.

   An obvious way to do this is by storing the elements of the matrix as
triplets, with two elements being the of the position in the array
(rows and column) and the third being the data itself. This is
conceptually easy to grasp, but requires more storage than is strictly
needed.

   The storage technique used within Octave is compressed column
format.  In this format the position of each element in a row and the
data are stored as previously. However, if we assume that all elements
in the same column are stored adjacent in the computers memory, then we
only need to store information on the number of non-zero elements in
each column, rather than their positions. Thus assuming that the matrix
has more non-zero elements than there are columns in the matrix, we win
in terms of the amount of memory used.

   In fact, the column index contains one more element than the number
of columns, with the first element always being zero. The advantage of
this is a simplication in the code, in that their is no special case
for the first or last columns. A short example, demonstrating this in C
is.

       for (j = 0; j < nc; j++)
         for (i = cidx (j); i < cidx(j+1); i++)
            printf ("non-zero element (%i,%i) is %d\n", ridx(i), j, data(i));

   A clear understanding might be had by considering an example of how
the above applies to an example matrix. Consider the matrix

         1   2   0  0
         0   0   0  3
         0   0   0  4

   The non-zero elements of this matrix are

        (1, 1)  => 1
        (1, 2)  => 2
        (2, 4)  => 3
        (3, 4)  => 4

   This will be stored as three vectors CIDX, RIDX and DATA,
representing the column indexing, row indexing and data respectively.
The contents of these three vectors for the above matrix will be

       CIDX = [0, 2, 2, 4]
       RIDX = [0, 0, 1, 2]
       DATA = [1, 2, 3, 4]

   Note that this is the representation of these elements with the
first row and column assumed to start as zero. Thus the number of
elements in the I-th column is given by `CIDX (I + 1) - CIDX (I)'.

   It should be noted that compressed row formats are equally possible.
However, in the context of mixed operations between mixed sparse and
dense matrices, it makes sense that the elements of the sparse matrices
are in the same order as the dense matrices. Octave stores dense
matrices in column major ordering, and so sparse matrices are equally
stored in this manner.

   A further constraint on the sparse matrix storage used by Octave is
that all elements in the rows are stored in increasing order of their
row index. This makes certain operations, later be faster. However, it
imposes the need to sort the elements on the creation of sparse
matrices. Having dis-ordered elements is potentially an advantage in
that it makes operations such as concatenating two sparse matrices
together easier and faster, however it adds complexity and speed
problems elsewhere.

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

   (1) Youcef Saad "SPARSKIT: A basic toolkit for sparse matrix
computation", 1994,
`ftp://ftp.cs.umn.edu/dept/sparse/SPARSKIT2/DOC/paper.ps'


File: octave.info,  Node: Creation,  Next: Operators and Functions,  Prev: Storage,  Up: Basics

22.1.2 Creating Sparse Matrices
-------------------------------

There are several means to create sparse matrix.

Returned from a function
     There are many functions that directly return sparse matrices.
     These include "speye", "sprand", "spdiag", etc.

Constructed from matrices or vectors
     The function "sparse" allows a sparse matrix to be constructed from
     three vectors representing the row, column and data.
     ALternatively, the function "spconvert" uses a three column matrix
     format to allow easy importation of data from elsewhere.

Created and then filled
     The function "sparse" or "spalloc" can be used to create an empty
     matrix that is then filled by the user

From a user binary program
     The user can directly create the sparse matrix within an oct-file.

   There are several basic functions to return specific sparse
matrices. For example the sparse identity matrix, is a matrix that is
often needed. It therefore has its own function to create it as `speye
(N)' or `speye (R, C)', which creates an N-by-N or R-by-C sparse
identity matrix.

   Another typical sparse matrix that is often needed is a random
distribution of random elements. The functions "sprand" and "sprandn"
perform this for uniform and random distributions of elements. They
have exactly the same calling convention as `sprand (R, C, D)', which
creates an R-by-C sparse matrix a density of filled elements of D.

   Other functions of interest that directly creates a sparse matrix,
are "spdiag" or its generalization "spdiags", that can take the
definition of the diagonals of the matrix and create the sparse matrix
that corresponds to this. For example

     s = spdiag (randn(1,n), -1);

   creates a sparse (N+1)-by-(N+1) sparse matrix with a single diagonal
defined.

   The recommended way for the user to create a sparse matrix, is to
create two vectors contain the row and column index of the data and a
third vector of the same size containing the data to be stored. For
example

      function x = foo (r, j)
       idx = randperm (r);
       x = ([zeros(r-2,1); rand(2,1)])(idx);
      endfunction

      ri = [];
      ci = [];
      d = [];

      for j=1:c
         dtmp = foo (r, j);  # Returns vector of length r with (:,j) values
         idx = find (dtmp != 0.);
         ri = [ri; idx];
         ci = [ci; j*ones(length(idx),1)];
         d = [d; dtmp(idx)];
      endfor
      s = sparse (ri, ci, d, r, c);

   creates an R-by-C sparse matrix with a random distribution of 2
elements per row. The elements of the vectors do not need to be sorted
in any particular order as Octave will store them prior to storing the
data. However, per sorting the data will make teh creation of the sparse
matrix faster.

   The function "spconvert" takes a three or four column real matrix.
The first two columns represent the row and column index respectively
and the third and four columns, the real and imaginary parts of the
sparse matrix. The matrix can contain zero elements and the elements
can be sorted in any order. Adding zero elements is a convenient way to
define the size of the sparse matrix. For example

     s = spconvert ([1 2 3 4; 1 3 4 4; 1 2 3 0]')
     => Compressed Column Sparse (rows=4, cols=4, nnz=3)
           (1 , 1) -> 1
           (2 , 3) -> 2
           (3 , 4) -> 3

   An example of creating and filling a matrix might be

     k = 5;
     nz = r * k;
     s = spalloc (r, c, nz)
     for j = 1:c
       idx = randperm (r);
       s (:, j) = [zeros(r - k, 1); rand(k, 1)] (idx);
     endfor

   It should be noted, that due to the way that the Octave assignment
functions are written that the assignment will reallocate the memory
used by the sparse matrix at each iteration. Therefore the "spalloc"
function ignores the NZ argument and does not preassign the memory for
the matrix. Therefore, it is vitally important that code using to above
structure should be as vectorized as possible to minimize the number of
assignments and reduce the number of memory allocations.

   The above problem can be avoided in oct-files. However, the
construction of a sparse matrix from an oct-file is more complex than
can be discussed in this brief introduction, and you are referred to
section *Note Oct-Files::, to have a full description of the techniques
involved.


File: octave.info,  Node: Operators and Functions,  Next: Information,  Prev: Creation,  Up: Basics

22.1.3 Basic Operators and Functions on Sparse Matrices
-------------------------------------------------------

* Menu:

* Functions:: Operators and Functions
* ReturnType:: The Return Types of Operators and Functions
* MathConsiderations:: Mathematical Considerations


File: octave.info,  Node: Functions,  Next: ReturnType,  Prev: Operators and Functions,  Up: Operators and Functions

22.1.3.1 Operators and Functions
................................

WRITE ME


File: octave.info,  Node: ReturnType,  Next: MathConsiderations,  Prev: Functions,  Up: Operators and Functions

22.1.3.2 The Return Types of Operators and Functions
....................................................

The two basic reason to use sparse matrices are to reduce the memory
usage and to not have to do calculations on zero elements. The two are
closely related in that the computation time on a sparse matrix operator
or function is roughly linear with the numberof non-zero elements.

   Therefore, there is a certain density of non-zero elements of a
matrix where it no longer makes sense to store it as a sparse matrix,
but rather as a full matrix. For this reason operators and functions
that have a high probability of returning a full matrix will always
return one. For example adding a scalar constant to a sparse matrix
will almost always make it a full matrix, and so the example

     speye(3) + 0
     =>   1  0  0
       0  1  0
       0  0  1

   returns a full matrix as can be seen. Additionally all sparse
functions test the amount of memory occupied by the sparse matrix to
see if the amount of storage used is larger than the amount used by the
full equivalent. Therefore `speye (2) * 1' will return a full matrix as
the memory used is smaller for the full version than the sparse version.

   As all of the mixed operators and functions between full and sparse
matrices exist, in general this does not cause any problems. However,
one area where it does cause a problem is where a sparse matrix is
promoted to a full matrix, where subsequent operations would resparsify
the matrix. Such cases as rare, but can be artificially created, for
example `(fliplr(speye(3)) + speye(3)) - speye(3)' gives a full matrix
when it should give a sparse one. In general, where such cases occur,
they impose only a small memory penalty.

   There is however one known case where this behaviour of Octave's
sparse matrices will cause a problem. That is in the handling of the
"diag" function. Whether "diag" returns a sparse or full matrix
depending on the type of its input arguments. So

      a = diag (sparse([1,2,3]), -1);

   should return a sparse matrix. To ensure this actually happens, the
"sparse" function, and other functions based on it like "speye", always
returns a sparse matrix, even if the memory used will be larger than
its full representation.


File: octave.info,  Node: MathConsiderations,  Prev: ReturnType,  Up: Operators and Functions

22.1.3.3 Mathematical Considerations
....................................

The attempt has been made to make sparse matrices behave in exactly the
same manner as there full counterparts. However, there are certain
differences and especially differences with other products sparse
implementations.

   Firstly, the "./" and ".^" operators must be used with care.
Consider what the examples

       s = speye (4);
       a1 = s .^ 2;
       a2 = s .^ s;
       a3 = s .^ -2;
       a4 = s ./ 2;
       a5 = 2 ./ s;
       a6 = s ./ s;

   will give. The first example of S raised to the power of 2 causes no
problems. However S raised element-wise to itself involves a a large
number of terms `0 .^ 0' which is 1. There `S .^ S' is a full matrix.

   Likewise `S .^ -2' involves terms terms like `0 .^ -2' which is
infinity, and so `S .^ -2' is equally a full matrix.

   For the "./" operator `S ./ 2' has no problems, but `2 ./ S'
involves a large number of infinity terms as well and is equally a full
matrix. The case of `S ./ S' involves terms like `0 ./ 0' which is a
`NaN' and so this is equally a full matrix with the zero elements of S
filled with `NaN' values.

   The above behaviour is consistent with full matrices, but is not
consistent with sparse implementations in other products.

   A particular problem of sparse matrices comes about due to the fact
that as the zeros are not stored, the sign-bit of these zeros is
equally not stored... In certain cases the sign-bit of zero is
important. For example

      a = 0 ./ [-1, 1; 1, -1];
      b = 1 ./ a
      => -Inf            Inf
          Inf           -Inf
      c = 1 ./ sparse (a)
      =>  Inf            Inf
          Inf            Inf

   To correct this behaviour would mean that zero elements with a
negative sign-bit would need to be stored in the matrix to ensure that
their sign-bit was respected. This is not done at this time, for
reasons of efficient, and so the user is warned that calculations where
the sign-bit of zero is important must not be done using sparse
matrices.

   Also discuss issues of fill-in. Discuss symamd etc, and mention
randperm that is included  elsewhere in the docs...

   WRITE ME


File: octave.info,  Node: Information,  Prev: Operators and Functions,  Up: Basics

22.1.4 Finding out Information about Sparse Matrices
----------------------------------------------------

Talk about the spy, spstats, nnz, spparms, etc function

   WRITE ME


File: octave.info,  Node: Graph Theory,  Next: Sparse Linear Algebra,  Prev: Basics,  Up: Sparse Matrices

22.2 Graphs are their use with Sparse Matrices
==============================================

Someone who knows more about this than me should write this...

   WRITE ME


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

22.3 Linear Algebra on Sparse Matrices
======================================

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

   The selection tree for how the linear equation is solve is

  1. If the matrix is not square go to 9.

  2. If the matrix is diagonal, solve directly and goto 9

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

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

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

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

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

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

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

  5. If the matrix is upper or lower triangular perform a sparse forward
     or backward subsitution, and goto 9

  6. If the matrix is a upper triangular matrix with column permutations
     or lower triangular matrix with row permutations, perform a sparse
     forward or backward subsitution, and goto 9

  7. If the matrix is hermitian with a real positive diagonal, attempt
     sparse Cholesky factorization.

     FIXME: Detection of positive definite matrices written and tested,
     but    Cholesky factorization isn't yet written

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

  9. If the matrix is not square, or any of the previous solvers flags
     a singular or near singular matrix, find a minimum norm solution

     FIXME: QR solvers not yet written.


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

   All of the solvers above, expect the banded solvers, calculate an
estimate of the condition number. This can be used to detect numerical
stability problems in the solution and force a minimum norm solution to
be used. However, for narrow banded matrices, the cost of calculating
the condition number is significant, and can in fact exceed the cost of
factoring the matrix. Therefore the condition number is not calculated
for banded matrices, and therefore unless the factorization is exactly
singular, these numerical instabilities won't be detected.  In cases
where, this might be a problem the user is recommended to disable the
banded solvers as above, at a significant cost in terms of speed.

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


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

22.4 Iterative Techniques applied to sparse matrices
====================================================

WRITE ME


File: octave.info,  Node: Oct-Files,  Next: License,  Prev: Iterative Techniques,  Up: Sparse Matrices

22.5 Using Sparse Matrices in Oct-files
=======================================

An oct-file is a means of writing an Octave function in a compilable
language like C++, rather than as a script file. This results in a
significant acceleration in the code.  It is not the purpose of this
section to discuss how to write an oct-file, or discuss what they are.
There are already two (1) very good references on oct-files themselves.
Users who are not familiar with oct-files are urged to read these
references to fully understand this chapter. The examples discussed
here assume that the oct-file is written entirely in C++.

   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 boolen 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 familar 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 similar 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:

* OctDifferences:: The Differences between the Array and Sparse Classes
* OctCreation:: Creating Spare Matrices in Oct-Files
* OctUse:: Using Sparse Matrices in Oct-Files

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

   (1) Paul Thomas "Dal Segno al Coda - The octave dynamically linked
function cookbook", `http://perso.wanadoo.fr/prthomas/intro.html', and
Cristophe Spiel "Del Coda Al Fine - Pushing Octave's Limits",
`http://octave.sourceforge.net/coda/coda.pdf'


File: octave.info,  Node: OctDifferences,  Next: OctCreation,  Prev: Oct-Files,  Up: Oct-Files

22.5.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 large that the
representation of the 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 hapening 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 seperate 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
repect the sparse matrix compressed column format discussed previous.


File: octave.info,  Node: OctCreation,  Next: OctUse,  Prev: OctDifferences,  Up: Oct-Files

22.5.2 Creating Spare Matrices in Oct-Files
-------------------------------------------

The user has several alternatives in how to create a sparse matrix.
They 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, they can create a sparse matrix with the appropriate
amount of space and then fill in the values. Both techniques have their
advantages and disadvantages.

   An example of how to create a small sparse matrix with the first
technique might be seen the example

       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 not illegal 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 legal. 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 not illegal to create a sparse matrix with
too much storage, so having NZ above equaling 6 is also legal.  The
disadvantage is that the matrix occupies more memory than strictly
needed.

   It is not always easy to known 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_mutate ();  // 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: OctUse,  Prev: OctCreation,  Up: Oct-Files

22.5.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: License,  Next: Function Reference,  Prev: Oct-Files,  Up: Sparse Matrices

22.6 Licensing of Third Party Software
======================================

There are several third party software packages used by the Octave
sparse matrix.

COLAMD
     is used for the "colamd" and "symamd" functions.

    Authors
          The authors of the code itself are Stefan I. Larimore and
          Timothy A.  Davis (davis@cise.ufl.edu), University of
          Florida.  The algorithm was developed in collaboration with
          John Gilbert, Xerox PARC, and Esmond Ng, Oak Ridge National
          Laboratory.

    License
          Copyright (C) 1998-2003 by the University of Florida.  All
          Rights Reserved.

          THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY
          EXPRESSED OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.

          Permission is hereby granted to use, copy, modify, and/or
          distribute this program, provided that the Copyright, this
          License, and the Availability of the original version is
          retained on all copies and made accessible to the end-user of
          any code or package that includes COLAMD or any modified
          version of COLAMD.

    Availability
          `http://www.cise.ufl.edu/research/sparse/colamd/'

UMFPACK
     is used in various places with the sparse types, including the LU
     decomposition and solvers.

    License
          UMFPACK Version 4.4 (Jan. 28, 2005), Copyright (C) 2005 by
          Timothy A. Davis.  All Rights Reserved.

          Your use or distribution of UMFPACK or any modified version of
          UMFPACK implies that you agree to this License.

          THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY
          EXPRESSED OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.

          Permission is hereby granted to use or copy this program,
          provided that the Copyright, this License, and the
          Availability of the original version is retained on all
          copies.  User documentation of any code that uses UMFPACK or
          any modified version of UMFPACK code must cite the Copyright,
          this License, the Availability note, and 'Used by permission.'
          Permission to modify the code and to distribute modified code
          is granted, provided the Copyright, this License, and the
          Availability note are retained, and a notice that the code
          was modified is included.  This software was developed with
          support from the National Science Foundation, and is provided
          to you free of charge.

    Availability
          `http://www.cise.ufl.edu/research/sparse/umfpack/'


File: octave.info,  Node: Function Reference,  Prev: License,  Up: Sparse Matrices

22.7 Function Reference
=======================

* Menu:

* colamd::	Column approximate minimum degree permutation.
* colperm::	Returns the column permutations such that the columns of `S
		(:, P)' are ordered in terms of increase number of non-zero
		elements.
* dmperm::	Perfrom a Deulmage-Mendelsohn permutation on the sparse
		matrix S.
* etree::	Returns the elimination tree for the matrix S.
* full::	returns a full storage matrix from a sparse one See also:
		sparse
* issparse::	Return 1 if the value of the expression EXPR is a sparse
		matrix.
* luinc::	Produce the incomplete LU factorization of the sparse
		A.
* matrix_type:: Identify the matrix type or mark a matrix as a particular
		type.
* nnz:: 	returns number of non zero elements in SM See also: sparse
* nonzeros::	Returns a vector of the non-zero values of the sparse
		matrix S
* nzmax::	Returns the amount of storage allocated to the sparse
		matrix SM.
* spalloc::	Returns an empty sparse matrix of size R-by-C.
* sparse::	SPARSE: create a sparse matrix
* spatan2::	Compute atan (Y / X) for corresponding sparse matrix
		elements of Y and X.
* spconvert::	This function converts for a simple sparse matrix format
		easily produced by other programs into Octave's internal
		sparse format.
* spcumprod::	Cumulative product of elements along dimension DIM.
* spcumsum::	Cumulative sum of elements along dimension DIM.
* spdet::	Compute the determinant of sparse matrix A using UMFPACK.
* spdiag::	Return a diagonal matrix with the sparse vector V on
		diagonal K.
* spdiags::	A generalization of the function `spdiag'.
* speye::	Returns a sparse identity matrix.
* spfind::	SPFIND: a sparse version of the find operator 1.
* spfun::	Compute `f(X)' for the non-zero values of X This results in
		a sparse matrix with the same structure as X.
* spinv::	Compute the inverse of the square matrix A.
* spkron::	Form the kronecker product of two sparse matrices.
* splu::	Compute the LU decomposition of the sparse matrix A, using
		subroutines from UMFPACK.
* spmax::	For a vector argument, return the maximum value.
* spmin::	For a vector argument, return the minimum value.
* spones::	Replace the non-zero entries of X with ones.
* spparms::	Sets or displays the parameters used by the sparse solvers
		and factorization functions.
* spprod::	Product of elements along dimension DIM.
* sprand::	Generate a random sparse matrix.
* sprandn::	Generate a random sparse matrix.
* spreshape::	Return a sparse matrix with M rows and N columns whose
		elements are taken from the sparse matrix A.
* spstats::	Return the stats for the non-zero elements of the sparse
		matrix S COUNT is the number of non-zeros in each column,
		MEAN is the mean of the non-zeros in each column, and VAR
		is the variance of the non-zeros in each column
* spsum::	Sum of elements along dimension DIM.
* spsumsq::	Sum of squares of elements along dimension DIM.
* spy:: 	Plot the sparsity pattern of the sparse matrix X
* symamd::	For a symmetric positive definite matrix S, returns the
		permutation vector p such that `S (P, P)' tends to have a
		sparser Cholesky factor than S.
* symbfact::	Performs a symbolic factorization analysis on the sparse
		matrix S.
* symrcm::	Returns the Reverse Cuthill McKee reordering of the sparse
		matrix S.


File: octave.info,  Node: colamd,  Next: colperm,  Up: Function Reference

22.7.0.1 colamd
...............

 -- Loadable Function: P = colamd (S)
 -- Loadable Function: P = colamd (S, KNOBS)
 -- Loadable Function: [P, STATS] = colamd (S)
 -- Loadable Function: [P, STATS] = colamd (S, KNOBS)
     Column approximate minimum degree permutation. `P = colamd (S)'
     returns the column approximate minimum degree permutation vector
     for the sparse matrix S. For a non-symmetric matrix S, `S (:,P)'
     tends to have sparser LU factors than S.  The Cholesky
     factorization of `S (:,P)' * S (:,P)' also tends to be sparser
     than that of `S' * S'.

     KNOBS is an optional two-element input vector. If S is m-by-n,
     then rows with more than `(KNOBS (1)) * N' entries are ignored.
     Columns with more than `(KNOBS (2)) * M' entries are removed prior
     to ordering, and ordered last in the output permutation P. If the
     knobs parameter is not present, then 0.5 is used instead, for both
     `KNOBS (1)' and `KNOBS (2)'. `KNOBS (3)' controls the printing of
     statistics and error messages.

     STATS is an optional 20-element output vector that provides data
     about the ordering and the validity of the input matrix S. Ordering
     statistics are in `STATS (1:3)'. `STATS (1)' and `STATS (2)' are
     the number of dense or empty rows and columns ignored by COLAMD
     and `STATS (3)' is the number of garbage collections performed on
     the internal data structure used by COLAMD (roughly of size `2.2 *
     nnz(S) + 4 * M + 7 * N' integers).

     Octave built-in functions are intended to generate valid sparse
     matrices, with no duplicate entries, with ascending row indices of
     the nonzeros in each column, with a non-negative number of entries
     in each column (!)  and so on.  If a matrix is invalid, then
     COLAMD may or may not be able to continue.  If there are duplicate
     entries (a row index appears two or more times in the same column)
     or if the row indices in a column are out of order, then COLAMD
     can correct these errors by ignoring the duplicate entries and
     sorting each column of its internal copy of the matrix S (the
     input matrix S is not repaired, however). If a matrix is invalid
     in other ways then COLAMD cannot continue, an error message is
     printed, and no output arguments (P or STATS) are returned.
     COLAMD is thus a simple way to check a sparse matrix to see if it's
     valid.

     `STATS (4:7)' provide information if COLAMD was able to continue.
     The matrix is OK if `STATS (4)' is zero, or 1 if invalid. `STATS
     (5)' is the rightmost column index that is unsorted or contains
     duplicate entries, or zero if no such column exists.  `STATS (6)'
     is the last seen duplicate or out-of-order row index in the column
     index given by `STATS (5)', or zero if no such row index exists.
     `STATS (7)' is the number of duplicate or out-of-order row
     indices. `STATS (8:20)' is always zero in the current version of
     COLAMD (reserved for future use).

     The ordering is followed by a column elimination tree
     post-ordering.

     The authors of the code itself are Stefan I. Larimore and Timothy
     A.  Davis (davis@cise.ufl.edu), University of Florida.  The
     algorithm was developed in collaboration with John Gilbert, Xerox
     PARC, and Esmond Ng, Oak Ridge National Laboratory. (see
     `http://www.cise.ufl.edu/research/sparse/colamd')


File: octave.info,  Node: colperm,  Next: dmperm,  Prev: colamd,  Up: Function Reference

22.7.0.2 colperm
................

 -- Function File: P = colperm (S)
     Returns the column permutations such that the columns of `S (:,
     P)' are ordered in terms of increase number of non-zero elements.
     If S is symmetric, then P is chosen such that `S (P, P)' orders
     the rows and columns with increasing number of non zeros elements.


File: octave.info,  Node: dmperm,  Next: etree,  Prev: colperm,  Up: Function Reference

22.7.0.3 dmperm
...............


File: octave.info,  Node: etree,  Next: full,  Prev: dmperm,  Up: Function Reference

22.7.0.4 etree
..............

 -- Loadable Function: P = etree (S)
 -- Loadable Function: P = etree (S, TYP)
 -- Loadable Function: [P, Q] = etree (S, TYP)
     Returns the elimination tree for the matrix S. By default S is
     assumed to be symmetric and the symmetric elimination tree is
     returned. The argument TYP controls whether a symmetric or column
     elimination tree is returned. Valid values of TYP are 'sym' or
     'col', for symmetric or column elimination tree respectively

     Called with a second argument, "etree" also returns the postorder
     permutations on the tree.


File: octave.info,  Node: full,  Next: issparse,  Prev: etree,  Up: Function Reference

22.7.0.5 full
.............

 -- Loadable Function: FM = full (SM)
     returns a full storage matrix from a sparse one



File: octave.info,  Node: issparse,  Next: luinc,  Prev: full,  Up: Function Reference

22.7.0.6 issparse
.................

 -- Loadable Function:  issparse (EXPR)
     Return 1 if the value of the expression EXPR is a sparse matrix.


File: octave.info,  Node: luinc,  Next: matrix_type,  Prev: issparse,  Up: Function Reference

22.7.0.7 luinc
..............

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

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

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

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

     OPTS is a structure containing one or more of the fields

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

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

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

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

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


File: octave.info,  Node: matrix_type,  Next: nnz,  Prev: luinc,  Up: Function Reference

22.7.0.8 matrix_type
....................

 -- Loadable Function: TYPE = matrix_type (A)
 -- Loadable Function: A = matrix_type (A, TYPE)
 -- Loadable Function: A = matrix_type (A, 'upper', PERM)
 -- Loadable Function: A = matrix_type (A, 'lower', PERM)
 -- Loadable Function: A = matrix_type (A, 'banded', NL, NU)
     Identify the matrix type or mark a matrix as a particular type.
     This allows rapid for solutions of linear equations involving A to
     be performed. Called with a single argument, `matrix_type' returns
     the type of the matrix and caches it for future use. Called with
     more than one argument, `matrix_type' allows the type of the
     matrix to be defined.

     The possible matrix types depend on whether the matrix is full or
     sparse, and can be one of the following

    'unknown'
          Remove any previously cached matrix type, and mark type as
          unknown

    'full'
          Mark the matrix as full.

    'positive definite'
          Full positive definite matrix.

    'diagonal'
          Diagonal Matrix. (Sparse matrices only)

    'permuted diagonal'
          Permuted Diagonal matrix. The permutation does not need to be
          specifically indicated, as the structure of the matrix
          explicitly gives this. (Sparse matrices only)

    'upper'
          Upper triangular. If the optional third argument PERM is
          given, the matrix is assumed to be a permuted upper
          triangular with the permutations defined by the vector PERM.

    'lower'
          Lower triangular. If the optional third argument PERM is
          given, the matrix is assumed to be a permuted lower
          triangular with the permutations defined by the vector PERM.

    'banded'
    'banded positive definite'
          Banded matrix with the band size of NL below the diagonal and
          NU above it. If NL and NU are 1, then the matrix is
          tridiagonal and treated with specialized code. In addition
          the matrix can be marked as positive definite (Sparse
          matrices only)

    'singular'
          The matrix is assumed to be singular and will be treated with
          a minimum norm solution


     Note that the matrix type will be discovered automatically on the
     first attempt to solve a linear equation involving A. Therefore
     `matrix_type' is only useful to give Octave hints of the matrix
     type. Incorrectly defining the matrix type will result in
     incorrect results from solutions of linear equations, and so it is
     entirely the responsibility of the user to correctly indentify the
     matrix type.


File: octave.info,  Node: nnz,  Next: nonzeros,  Prev: matrix_type,  Up: Function Reference

22.7.0.9 nnz
............

 -- Loadable Function: SCALAR = nnz (SM)
     returns number of non zero elements in SM



File: octave.info,  Node: nonzeros,  Next: nzmax,  Prev: nnz,  Up: Function Reference

22.7.0.10 nonzeros
..................

 -- Function File:  nonzeros (S)
     Returns a vector of the non-zero values of the sparse matrix S.


File: octave.info,  Node: nzmax,  Next: spalloc,  Prev: nonzeros,  Up: Function Reference

22.7.0.11 nzmax
...............

 -- Loadable Function: SCALAR = nzmax (SM)
     Return the amount of storage allocated to the sparse matrix SM.
     Note that Octave tends to crop unused memory at the first
     oppurtunity for sparse objects. There are some cases of user
     created sparse objects where the value returned by "nzmaz" will
     not be the same as "nnz", but in general they will give the same
     result.



File: octave.info,  Node: spalloc,  Next: sparse,  Prev: nzmax,  Up: Function Reference

22.7.0.12 spalloc
.................

 -- Function File: S = spalloc (R, C, NZ)
     Returns an empty sparse matrix of size R-by-C. As Octave resizes
     sparse matrices at the first opportunity, so that no additional
     space is needed, the argument NZ is ignored. This function is
     provided only for compatiability reasons.

     It should be noted that this means that code like

          k = 5;
          nz = r * k;
          s = spalloc (r, c, nz)
          for j = 1:c
            idx = randperm (r);
            s (:, j) = [zeros(r - k, 1); rand(k, 1)] (idx);
          endfor

     will reallocate memory at each step. It is therefore vitally
     important that code like this is vectorized as much as possible.


File: octave.info,  Node: sparse,  Next: spatan2,  Prev: spalloc,  Up: Function Reference

22.7.0.13 sparse
................

 -- Loadable Function: SPARSE_VAL = sparse (...)
     SPARSE: create a sparse matrix

     sparse can be called in the following ways:

       1. S = sparse(A)  where A is a full matrix

       2. S = sparse(A,1)  where A is a full matrix, result is forced
          back to a full matrix is resulting matrix is sparse

       3. S = sparse(I,J,S,M,N,NZMAX)  where
               I,J   are integer index vectors (1 x nnz)
               S     is the vector of real or complex entries (1 x nnz)
               M,N   are the scalar dimentions of S
               NZMAX is ignored (here for compatability with Matlab)
               if multiple values are specified with the same I,J
                position, the corresponding values in S will be added

       4. The following usages are equivalent to (2) above:
               S = sparse(I,J,S,M,N)
               S = sparse(I,J,S,M,N,'summation')
               S = sparse(I,J,S,M,N,'sum')

       5. S = sparse(I,J,S,M,N,'unique')
               same as (2) above, except that rather than adding, if
               more than two values are specified for the same I,J
               position, then the last specified value will be kept

       6. S=  sparse(I,J,SV)          uses M=max(I), N=max(J)

       7. S=  sparse(M,N)            does sparse([],[],[],M,N,0)

          SV, and I or J may be scalars, in which case they are
          expanded to all have the same length



File: octave.info,  Node: spatan2,  Next: spconvert,  Prev: sparse,  Up: Function Reference

22.7.0.14 spatan2
.................

 -- Loadable Function:  spatan2 (Y, X)
     Compute atan (Y / X) for corresponding sparse matrix elements of Y
     and X.  The result is in range -pi to pi.


File: octave.info,  Node: spconvert,  Next: spcumprod,  Prev: spatan2,  Up: Function Reference

22.7.0.15 spconvert
...................

 -- Function File: X = spconvert (M)
     This function converts for a simple sparse matrix format easily
     produced by other programs into Octave's internal sparse format.
     The input X is either a 3 or 4 column real matrix, containing the
     row, column, real and imaginary parts of the elements of the
     sparse matrix. An element with a zero real and imaginay part can
     be used to force a particular matrix size.


File: octave.info,  Node: spcumprod,  Next: spcumsum,  Prev: spconvert,  Up: Function Reference

22.7.0.16 spcumprod
...................

 -- Loadable Function: Y = spcumprod (X,DIM)
     Cumulative product of elements along dimension DIM.  If DIM is
     omitted, it defaults to 1 (column-wise cumulative products).


File: octave.info,  Node: spcumsum,  Next: spdet,  Prev: spcumprod,  Up: Function Reference

22.7.0.17 spcumsum
..................

 -- Loadable Function: Y = spcumsum (X,DIM)
     Cumulative sum of elements along dimension DIM.  If DIM is
     omitted, it defaults to 1 (column-wise cumulative sums).


File: octave.info,  Node: spdet,  Next: spdiag,  Prev: spcumsum,  Up: Function Reference

22.7.0.18 spdet
...............

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


File: octave.info,  Node: spdiag,  Next: spdiags,  Prev: spdet,  Up: Function Reference

22.7.0.19 spdiag
................

 -- Loadable Function:  spdiag (V, K)
     Return a diagonal matrix with the sparse vector V on diagonal K.
     The second argument is optional. If it is positive, the vector is
     placed on the K-th super-diagonal. If it is negative, it is placed
     on the -K-th sub-diagonal.  The default value of K is 0, and the
     vector is placed on the main diagonal.  For example,

          spdiag ([1, 2, 3], 1)
          ans =

          Compressed Column Sparse (rows=4, cols=4, nnz=3)
            (1 , 2) -> 1
            (2 , 3) -> 2
            (3 , 4) -> 3



File: octave.info,  Node: spdiags,  Next: speye,  Prev: spdiag,  Up: Function Reference

22.7.0.20 spdiags
.................

 -- function File: [B, C] = spdiags (A)
 -- function File: B = spdiags (A, C)
 -- function File: B = spdiags (V, C, A)
 -- function File: B = spdiags (V, C, M, N)
     A generalization of the function `spdiag'. Called with a single
     input argument, the non-zero diagonals C of A are extracted.  With
     two arguments the diagonals to extract are given by the vector C.

     The other two forms of `spdiags' modify the input matrix by
     replacing the diagonals. They use the columns of V to replace the
     columns represented by the vector C. If the sparse matrix A is
     defined then the diagonals of this matrix are replaced.  Otherwise
     a matrix of M by N is created with the diagonals given by V.

     Negative values of C representive diagonals below the main
     diagonal, and positive values of C diagonals above the main
     diagonal.

     For example

          spdiags (reshape (1:12, 4, 3), [-1 0 1], 5, 4)
          =>    5 10  0  0
                1  6 11  0
                0  2  7 12
                0  0  3  8
                0  0  0  4



File: octave.info,  Node: speye,  Next: spfind,  Prev: spdiags,  Up: Function Reference

22.7.0.21 speye
...............

 -- Function File: Y = speye (M)
 -- Function File: Y = speye (M, N)
 -- Function File: Y = speye (SZ)
     Returns a sparse identity matrix. This is significantly more
     efficient than `sparse (eye (M))' as the full matrix is not
     constructed.

     Called with a single argument a square matrix of size M by M is
     created. Otherwise a matrix of M by N is created. If called with a
     single vector argument, this argument is taken to be the size of
     the matrix to create.


File: octave.info,  Node: spfind,  Next: spfun,  Prev: speye,  Up: Function Reference

22.7.0.22 spfind
................

 -- Loadable Function: [...] = spfind (...)
     SPFIND: a sparse version of the find operator
       1. X = spfind( A )
               is analagous to X= find(A(:))
               where A= full(A)


       2. [I,J,V,NR,NC] = spfind( A )
               returns column vectors I,J,V such that
               A= sparse(I,J,V,NR,NC)



File: octave.info,  Node: spfun,  Next: spinv,  Prev: spfind,  Up: Function Reference

22.7.0.23 spfun
...............

 -- Function File: Y = spfun (F,X)
     Compute `f(X)' for the non-zero values of X.  This results in a
     sparse matrix with the same structure as X. The function F can be
     passed as a string, a function handle or an inline function.


File: octave.info,  Node: spinv,  Next: spkron,  Prev: spfun,  Up: Function Reference

22.7.0.24 spinv
...............

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

     An optional second input argument Q is the optional pre-ordering of
     the matrix, such that `X = inv (A (:, Q))'. Q can equally be a
     matrix, in which case `X = inv (A * Q))'.

     If a third output argument is given then the permuations to
     achieve a sparse inverse are returned. It is not required that the
     return column permutations Q and the same as the user supplied
     permutations


File: octave.info,  Node: spkron,  Next: splu,  Prev: spinv,  Up: Function Reference

22.7.0.25 spkron
................

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

          x = [a(i, j) b]

     For example,

          kron (1:4, ones (3, 1))
                =>  1  2  3  4
                    1  2  3  4
                    1  2  3  4


File: octave.info,  Node: splu,  Next: spmax,  Prev: spkron,  Up: Function Reference

22.7.0.26 splu
..............

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

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

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

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


File: octave.info,  Node: spmax,  Next: spmin,  Prev: splu,  Up: Function Reference

22.7.0.27 spmax
...............

 -- Mapping Function:  spmax (X, Y, DIM)
 -- Mapping Function: [W, IW] = spmax (X)
     For a vector argument, return the maximum value.  For a matrix
     argument, return the maximum value from each column, as a row
     vector, or over the dimension DIM if defined. For two matrices (or
     a matrix and scalar), return the pair-wise maximum.  Thus,

          max (max (X))

     returns the largest element of X, and

          max (2:5, pi)
              =>  3.1416  3.1416  4.0000  5.0000
     compares each element of the range `2:5' with `pi', and
     returns a row vector of the maximum values.

     For complex arguments, the magnitude of the elements are used for
     comparison.

     If called with one input and two output arguments, `max' also
     returns the first index of the maximum value(s). Thus,

          [x, ix] = max ([1, 3, 5, 2, 5])
              =>  x = 5
                  ix = 3


File: octave.info,  Node: spmin,  Next: spones,  Prev: spmax,  Up: Function Reference

22.7.0.28 spmin
...............

 -- Mapping Function:  spmin (X, Y, DIM)
 -- Mapping Function: [W, IW] = spmin (X)
     For a vector argument, return the minimum value.  For a matrix
     argument, return the minimum value from each column, as a row
     vector, or over the dimension DIM if defined. For two matrices (or
     a matrix and scalar), return the pair-wise minimum.  Thus,

          min (min (X))

     returns the smallest element of X, and

          min (2:5, pi)
              =>  2.0000  3.0000  3.1416  3.1416
     compares each element of the range `2:5' with `pi', and
     returns a row vector of the minimum values.

     For complex arguments, the magnitude of the elements are used for
     comparison.

     If called with one input and two output arguments, `min' also
     returns the first index of the minimum value(s). Thus,

          [x, ix] = min ([1, 3, 0, 2, 5])
              =>  x = 0
                  ix = 3


File: octave.info,  Node: spones,  Next: spparms,  Prev: spmin,  Up: Function Reference

22.7.0.29 spones
................

 -- Function File: Y = spones (X)
     Replace the non-zero entries of X with ones. This creates a sparse
     matrix with the same structure as X.


File: octave.info,  Node: spparms,  Next: spprod,  Prev: spones,  Up: Function Reference

22.7.0.30 spparms
.................

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

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

        * ths_rel ?? (default 1)

        * ths_abs ?? (default 1)

        * exact_d ?? (default 0)

        * supernd ?? (default 3)

        * rreduce ?? (default 3)

        * wh_frac ?? (default 0.5)

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

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

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

        * bandden ?? (default 0.5)

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

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


File: octave.info,  Node: spprod,  Next: sprand,  Prev: spparms,  Up: Function Reference

22.7.0.31 spprod
................

 -- Loadable Function: Y = spprod (X,DIM)
     Product of elements along dimension DIM.  If DIM is omitted, it
     defaults to 1 (column-wise products).


File: octave.info,  Node: sprand,  Next: sprandn,  Prev: spprod,  Up: Function Reference

22.7.0.32 sprand
................

 -- Function File:  sprand (M, N, D)
 -- Function File:  sprand (S)
     Generate a random sparse matrix. The size of the matrix will be M
     by N, with a density of values given by D.  D should be between 0
     and 1. Values will be normally distributed with mean of zero and
     variance 1.

     Note: sometimes the actual density  may be a bit smaller than D.
     This is unlikely to happen for large really sparse matrices.

     If called with a single matrix argument, a random sparse matrix is
     generated wherever the matrix S is non-zero.


File: octave.info,  Node: sprandn,  Next: spreshape,  Prev: sprand,  Up: Function Reference

22.7.0.33 sprandn
.................

 -- Function File:  sprand (M, N, D)
 -- Function File:  sprand (S)
     Generate a random sparse matrix. The size of the matrix will be M
     by N, with a density of values given by D.  D should be between 0
     and 1. Values will be normally distributed with mean of zero and
     variance 1.

     Note: sometimes the actual density  may be a bit smaller than D.
     This is unlikely to happen for large really sparse matrices.

     If called with a single matrix argument, a random sparse matrix is
     generated wherever the matrix S is non-zero.


File: octave.info,  Node: spreshape,  Next: spstats,  Prev: sprandn,  Up: Function Reference

22.7.0.34 spreshape
...................


File: octave.info,  Node: spstats,  Next: spsum,  Prev: spreshape,  Up: Function Reference

22.7.0.35 spstats
.................

 -- Function File: [COUNT, MEAN, VAR] = spstats (S)
 -- Function File: [COUNT, MEAN, VAR] = spstats (S, J)
     Return the stats for the non-zero elements of the sparse matrix S.
     COUNT is the number of non-zeros in each column, MEAN is the mean
     of the non-zeros in each column, and VAR is the variance of the
     non-zeros in each column.

     Called with two output arguments, if S is the data and J is the
     bin number for the data, compute the stats for each bin.  In this
     case, bins can contain data values of zero, whereas with `spstats
     (S)' the zeros may disappear.


File: octave.info,  Node: spsum,  Next: spsumsq,  Prev: spstats,  Up: Function Reference

22.7.0.36 spsum
...............

 -- Loadable Function: Y = spsum (X,DIM)
     Sum of elements along dimension DIM.  If DIM is omitted, it
     defaults to 1 (column-wise sum).


File: octave.info,  Node: spsumsq,  Next: spy,  Prev: spsum,  Up: Function Reference

22.7.0.37 spsumsq
.................

 -- Loadable Function: Y = spsumsq (X,DIM)
     Sum of squares of elements along dimension DIM.  If DIM is
     omitted, it defaults to 1 (column-wise sum of squares).  This
     function is equivalent to computing
          spsum (x .* spconj (x), dim)
     but it uses less memory and avoids calling `spconj' if X is real.


File: octave.info,  Node: spy,  Next: symamd,  Prev: spsumsq,  Up: Function Reference

22.7.0.38 spy
.............

 -- Function File:  spy (X)
     Plot the sparsity pattern of the sparse matrix X.


File: octave.info,  Node: symamd,  Next: symbfact,  Prev: spy,  Up: Function Reference

22.7.0.39 symamd
................

 -- Loadable Function: P = symamd (S)
 -- Loadable Function: P = symamd (S, KNOBS)
 -- Loadable Function: [P, STATS] = symamd (S)
 -- Loadable Function: [P, STATS] = symamd (S, KNOBS)
     For a symmetric positive definite matrix S, returns the permutation
     vector p such that `S (P, P)' tends to have a sparser Cholesky
     factor than S. Sometimes SYMAMD works well for symmetric
     indefinite matrices too. The matrix S is assumed to be symmetric;
     only the strictly lower triangular part is referenced. S must be
     square.

     KNOBS is an optional input argument. If S is n-by-n, then rows and
     columns with more than `KNOBS (1) * N' entries are removed prior
     to ordering, and ordered last in the output permutation P. If the
     KNOBS parameter is not present, then the default of 0.5 is used
     instead. `KNOBS (2)' controls the printing of statistics and error
     messages.

     STATS is an optional 20-element output vector that provides data
     about the ordering and the validity of the input matrix S. Ordering
     statistics are in `STATS (1:3)'. `STATS (1) = STATS (2)' is the
     number of dense or empty rows and columns ignored by SYMAMD and
     `STATS (3)' is the number of garbage collections performed on the
     internal data structure used by SYMAMD (roughly of size `8.4 * nnz
     (tril (S, -1)) + 9 * N' integers).

     Octave built-in functions are intended to generate valid sparse
     matrices, with no duplicate entries, with ascending row indices of
     the nonzeros in each column, with a non-negative number of entries
     in each column (!)  and so on.  If a matrix is invalid, then
     SYMAMD may or may not be able to continue.  If there are duplicate
     entries (a row index appears two or more times in the same column)
     or if the row indices in a column are out of order, then SYMAMD
     can correct these errors by ignoring the duplicate entries and
     sorting each column of its internal copy of the matrix S (the
     input matrix S is not repaired, however).  If a matrix is invalid
     in other ways then SYMAMD cannot continue, an error message is
     printed, and no output arguments (P or STATS) are returned.
     SYMAMD is thus a simple way to check a sparse matrix to see if
     it's valid.

     `STATS (4:7)' provide information if SYMAMD was able to continue.
     The matrix is OK if `STATS (4)' is zero, or 1 if invalid. `STATS
     (5)' is the rightmost column index that is unsorted or contains
     duplicate entries, or zero if no such column exists. `STATS (6)'
     is the last seen duplicate or out-of-order row index in the column
     index given by `STATS (5)', or zero if no such row index exists.
     `STATS (7)' is the number of duplicate or out-of-order row
     indices. `STATS (8:20)' is always zero in the current version of
     SYMAMD (reserved for future use).

     The ordering is followed by a column elimination tree
     post-ordering.

     The authors of the code itself are Stefan I. Larimore and Timothy
     A.  Davis (davis@cise.ufl.edu), University of Florida.  The
     algorithm was developed in collaboration with John Gilbert, Xerox
     PARC, and Esmond Ng, Oak Ridge National Laboratory. (see
     `http://www.cise.ufl.edu/research/sparse/colamd')


File: octave.info,  Node: symbfact,  Next: symrcm,  Prev: symamd,  Up: Function Reference

22.7.0.40 symbfact
..................

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


File: octave.info,  Node: symrcm,  Prev: symbfact,  Up: Function Reference

22.7.0.41 symrcm
................


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

23 Quadrature
*************

* Menu:

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


File: octave.info,  Node: Functions of One Variable,  Next: Orthogonal Collocation,  Up: Quadrature

23.1 Functions of One Variable
==============================

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

          y = f (x)

     where Y and X are scalars.

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

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

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

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

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

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

     Options include

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

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

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

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

from X = 0 to X = 3.

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

   The first step is to define the function:

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

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

   Then we simply call quad:

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

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


File: octave.info,  Node: Orthogonal Collocation,  Prev: Functions of One Variable,  Up: Quadrature

23.2 Orthogonal Collocation
===========================

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

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

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

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

   Then the solution at the roots R is

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


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

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

Octave has two built-in functions for solving differential equations.
Both are based on reliable ODE solvers written in Fortran.

* Menu:

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


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

24.1 Ordinary Differential Equations
====================================

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

     dx
     -- = f (x, t)
     dt

using Hindmarsh's ODE solver LSODE.

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

          dx
          -- = f(x, t)
          dt

     with

          x(t_0) = x_0

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

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

          XDOT = f (X, T)

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

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

          JAC = j (X, T)

     in which JAC is the matrix of partial derivatives

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

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

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

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

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

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

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

     Options include

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

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

          The local error test applied at each integration step is

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

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

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

         "bdf"

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

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

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

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

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

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

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

     function xdot = f (x, t)

       xdot = zeros (3,1);

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

     endfunction

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

     t = linspace (0, 500, 1000);

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

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

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

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


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

24.2 Differential-Algebraic Equations
=====================================

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

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

using Petzold's DAE solver DASPK.

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

          0 = f (x, xdot, t)

     with

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

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

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

          RES = f (X, XDOT, T)

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

     If FCN is a two-element string array, the first element names the
     function f described above, and the second element names a
     function to compute the modified Jacobian

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

     The modified Jacobian function must have the form


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

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

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

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

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

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

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

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

     Options include

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

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

          The local error test applied at each integration step is

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

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

            1. Given Y_d, calculate Y_a and Y'_d

            2. Given Y', calculate Y.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            2. To enforce constraint checking during the integration.

            3. To enforce both options 1 and 2.

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

         -2
               Less than zero.

         -1
               Less than or equal to zero.

         0
               Not constrained.

         1
               Greater than or equal to zero.

         2
               Greater than zero.

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

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

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

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

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

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

          0 = f (x, xdot, t)

     with

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

     with functional stopping criteria (root solving).

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

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

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

          RES = f (X, XDOT, T)

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

     If FCN is a two-element string array, the first element names the
     function f described above, and the second element names a
     function to compute the modified Jacobian

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

     The modified Jacobian function must have the form


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

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

          G_OUT = g (X, T)

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

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

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

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

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

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

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

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

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

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

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

     Options include

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

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

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

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

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

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

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

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


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

25 Optimization
***************

* Menu:

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


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

25.1 Linear Programming
=======================


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

25.2 Quadratic Programming
==========================


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

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


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

25.4 Linear Least Squares
=========================

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

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

    BETA
          The GLS estimator for b.

    V
          The GLS estimator for s^2.

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

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

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

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

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

    SIGMA
          The OLS estimator for the matrix S,

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

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


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

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

I hope that someday Octave will include more statistics functions.  If
you would like to help improve Octave in this area, please contact
<bug@octave.org>.

* Menu:

* Basic Statistical Functions::
* Tests::
* Models::
* Distributions::


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

26.1 Basic Statistical Functions
================================

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

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

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

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

    `"g"'
          Computer the geometric mean.

    `"h"'
          Compute the harmonic mean.

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

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

 -- Function File:  median (X)
     If X is a vector, compute the median value of the elements of X.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

          moment (x, 3, "ac")

     computes the third central absolute moment of X.

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

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

 -- Function File:  logit (P)
     For each component of P, return the logit `log (P / (1-P))' of P.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

          - log (- log (X))

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


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

26.2 Tests
==========

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

     The output is a structure with the following elements:

    PVAL
          The p-value of the test.

    STAT
          The value of the test statistic.

    DIST
          The distribution of the test statistic.

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

    ALTERNATIVE
          The alternative hypothesis.

    METHOD
          The method used for testing.

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

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

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

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

     If not given explicitly, R = 0.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

26.3 Models
===========

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

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

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

     fits the model

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

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

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

     The full form is

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

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

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

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

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

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


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

26.4 Distributions
==================

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

     The arguments can be of common size or scalar.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

     The arguments must be of common size or scalar.

 -- Function File:  hypergeometric_rnd (N_SIZE, M, T, N)
 -- Function File:  hypergeometric_rnd (M, T, N, R, C)
 -- Function File:  hypergeometric_rnd (M, T, N, SZ)
     Generate a row vector containing a random sample of size N_SIZE
     from the hypergeometric distribution with parameters M, T, and N.

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

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

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

     for X > 0.

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

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

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

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

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

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

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

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

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

 -- Function File:  lognormal_cdf (X, A, V)
     For each element of X, compute the cumulative distribution
     function (CDF) at X of the lognormal distribution with parameters
     A and V.  If a random variable follows this distribution, its
     logarithm is normally distributed with mean `log (A)' and variance
     V.

     Default values are A = 1, V = 1.

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

     Default values are A = 1, V = 1.

 -- Function File:  lognormal_pdf (X, A, V)
     For each element of X, compute the probability density function
     (PDF) at X of the lognormal distribution with parameters A and V.
     If a random variable follows this distribution, its logarithm is
     normally distributed with mean `log (A)' and variance V.

     Default values are A = 1, V = 1.

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

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

 -- Function File:  normal_cdf (X, M, V)
     For each element of X, compute the cumulative distribution
     function (CDF) at X of the normal distribution with mean M and
     variance V.

     Default values are M = 0, V = 1.

 -- Function File:  normal_inv (X, M, V)
     For each element of X, compute the quantile (the inverse of the
     CDF) at X of the normal distribution with mean M and variance V.

     Default values are M = 0, V = 1.

 -- Function File:  normal_pdf (X, M, V)
     For each element of X, compute the probability density function
     (PDF) at X of the normal distribution with mean M and variance V.

     Default values are M = 0, V = 1.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

 -- Function File:  stdnormal_cdf (X)
     For each component of X, compute the CDF of the standard normal
     distribution at X.

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

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

 -- Function File:  stdnormal_rnd (R, C)
 -- Function File:  stdnormal_rnd (SZ)
     Return an R by C or `size (SZ)' matrix of random numbers from the
     standard normal distribution.

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

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

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

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

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

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

     Default values are A = 0, B = 1.

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

     Default values are A = 0, B = 1.

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

     Default values are A = 0, B = 1.

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

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

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

          1 - exp(-(x/sigma)^alpha)

     for X >= 0.

 -- Function File:  weibull_inv (X, LAMBDA, ALPHA)
     Compute the quantile (the inverse of the CDF) at X of the Weibull
     distribution with shape parameter ALPHA and scale parameter SIGMA.

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

             alpha * sigma^(-alpha) * x^(alpha-1) * exp(-(x/sigma)^alpha)

     for X > 0.

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

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

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

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


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

27 Financial Functions
**********************

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

 -- Function File:  vol (X, M, N)
     Return the volatility of each column of the input matrix X.  The
     number of data sets per period is given by M (e.g. the number of
     data per year if you want to compute the volatility per year).
     The optional parameter N gives the number of past periods used for
     computation, if it is omitted, a value of 1 is used.  If T is the
     number of rows of X, `vol' returns the volatility from `n*m' to T.


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

28 Sets
*******

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

 -- Function File:  create_set (X)
     Return a row vector containing the unique values in X, sorted in
     ascending order.  For example,

          create_set ([ 1, 2; 3, 4; 4, 2 ])
          => [ 1, 2, 3, 4 ]

 -- Function File:  union (X, Y)
     Return the set of elements that are in either of the sets X and Y.
     For example,

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

 -- Function File:  intersection (X, Y)
     Return the set of elements that are in both sets X and Y.  For
     example,

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

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

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


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

29 Polynomial Manipulations
***************************

In Octave, a polynomial is represented by its coefficients (arranged in
descending order).  For example, a vector  $c$ of length  N

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

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

     The companion matrix is

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

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

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

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

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

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

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

 -- Function File:  poly (A)
     If A is a square N-by-N matrix, `poly (A)' is the row vector of
     the coefficients of `det (z * eye (N) - a)', the characteristic
     polynomial of A.  If X is a vector, `poly (X)' is a vector of
     coefficients of the polynomial whose roots are the elements of X.

 -- Function File:  polyderiv (C)
 -- Function File: [Q] = polyder (B, A)
 -- Function File: [Q, R] = polyder (B, A)
     Return the coefficients of the derivative of the polynomial whose
     coefficients are given by vector C.  If a pair of polynomials is
     given B and A, the derivative of the product is returned in Q, or
     the quotient numerator in Q and the quotient denominator in R.

 -- Function File: [P, S] = polyfit (X, Y, N)
     Return the coefficients of a polynomial P(X) of degree N that
     minimizes `sumsq (p(x(i)) - y(i))',  to best fit the data in the
     least squares sense.

     The polynomial coefficients are returned in a row vector.

     If two output arguments are requested, the second is a structure
     containing the following fields:

    `R'
          The Cholesky factor of the Vandermonde matrix used to compute
          the polynomial coefficients.

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

    `df'
          The degrees of freedom.

    `normr'
          The norm of the residuals.

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

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

     The constant of integration is set to zero.

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

 -- Function File:  polyval (C, X)
     Evaluate a polynomial.

     `polyval (C, X)' will evaluate the polynomial at the specified
     value of X.

     If X is a vector or matrix, the polynomial is evaluated at each of
     the elements of X.

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

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

     The argument X must be a square matrix.

 -- Function File:  residue (B, A, TOL)
     If B and A are vectors of polynomial coefficients, then residue
     calculates the partial fraction expansion corresponding to the
     ratio of the two polynomials.  

     The function `residue' returns R, P, K, and E, where the vector R
     contains the residue terms, P contains the pole values, K contains
     the coefficients of a direct polynomial term (if it exists) and E
     is a vector containing the powers of the denominators in the
     partial fraction terms.

     Assuming B and A represent polynomials  P (s) and Q(s)  we have:

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

     where M is the number of poles (the length of the R, P, and E
     vectors) and N is the length of the K vector.

     The argument TOL is optional, and if not specified, a default
     value of 0.001 is assumed.  The tolerance value is used to
     determine whether poles with small imaginary components are
     declared real.  It is also used to determine if two poles are
     distinct.  If the ratio of the imaginary part of a pole to the
     real part is less than TOL, the imaginary part is discarded.  If
     two poles are farther apart than TOL they are distinct.  For
     example,

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

     which implies the following partial fraction expansion

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

 -- Function File:  roots (V)
     For a vector V with N components, return the roots of the
     polynomial

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

 -- Function File:  polyout (C, X)
     Write formatted polynomial
             c(x) = c(1) * x^n + ... + c(n) x + c(n+1)
      and return it as a string or write it to the screen (if NARGOUT
     is zero).  X defaults to the string `"s"'.


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

30 Control Theory
*****************

The Octave Control Systems Toolbox (OCST) was initially developed by
Dr. A. Scottedward Hodel <a.s.hodel@eng.auburn.edu> with the assistance
of his students
   * R. Bruce Tenison <btenison@dibbs.net>,

   * David C. Clem,

   * John E. Ingram <John.Ingram@sea.siemans.com>, and

   * Kristi McGowan.
   This development was supported in part by NASA's Marshall Space
Flight Center as part of an in-house CACSD environment.  Additional
important contributions were made by Dr. Kai Mueller
<mueller@ifr.ing.tu-bs.de> and Jose Daniel Munoz Frias (`place.m').

   An on-line menu-driven tutorial is available via `DEMOcontrol';
beginning OCST users should start with this program.

 -- Function File:  DEMOcontrol
     Octave Control Systems Toolbox demo/tutorial program.  The demo
     allows the user to select among several categories of OCST
     function:
          octave:1> DEMOcontrol
          O C T A V E    C O N T R O L   S Y S T E M S   T O O L B O X
          Octave Controls System Toolbox Demo

            [ 1] System representation
            [ 2] Block diagram manipulations
            [ 3] Frequency response functions
            [ 4] State space analysis functions
            [ 5] Root locus functions
            [ 6] LQG/H2/Hinfinity functions
            [ 7] End
     Command examples are interactively run for users to observe
     the use of OCST functions.

* Menu:

* sysstruct::
* sysinterface::
* sysdisp::
* blockdiag::
* numerical::
* sysprop::
* systime::
* sysfreq::
* cacsd::
* misc::


File: octave.info,  Node: sysstruct,  Next: sysinterface,  Up: Control Theory

30.1 System Data Structure
==========================

* Menu:

* sysstructvars::
* sysstructtf::
* sysstructzp::
* sysstructss::

   The OCST stores all dynamic systems in a single data structure
format that can represent continuous systems, discrete-systems, and
mixed (hybrid) systems in state-space form, and can also represent
purely continuous/discrete systems in either transfer function or
pole-zero form. In order to provide more flexibility in treatment of
discrete/hybrid systems, the OCST also keeps a record of which system
outputs are sampled.

   Octave structures are accessed with a syntax much like that used by
the C programming language.  For consistency in use of the data
structure used in the OCST, it is recommended that the system structure
access m-files be used (*note sysinterface::).  Some elements of the
data structure are absent depending on the internal system
representation(s) used.  More than one system representation can be
used for SISO systems; the OCST m-files ensure that all representations
used are consistent with one another.

 -- Function File:  sysrepdemo
     Tutorial for the use of the system data structure functions.


File: octave.info,  Node: sysstructvars,  Next: sysstructtf,  Up: sysstruct

30.1.1 Variables common to all OCST system formats
--------------------------------------------------

The data structure elements (and variable types) common to all  system
representations are listed below; examples of the initialization and
use of the system data structures are given in subsequent sections and
in the online demo `DEMOcontrol'.
N
NZ
     The respective number of continuous and discrete states in the
     system (scalar)

INNAME
OUTNAME
     list of name(s) of the system input, output signal(s). (list of
     strings)

SYS
     System status vector.  (vector)

     This vector indicates both what representation was used to
     initialize the system data structure (called the primary system
     type) and which other representations are currently up-to-date
     with the primary system type (*note structaccess::).

     The value of the first element of the vector indicates the primary
     system type.

    0
          for tf form (initialized with `tf2sys' or `fir2sys')

    1
          for zp form (initialized with `zp2sys')

    2
          for ss form (initialized with `ss2sys')

     The next three elements are boolean flags that indicate whether
     tf, zp, or ss, respectively, are "up to date" (whether it is safe
     to use the variables associated with these representations).
     These flags are changed when calls are made to the `sysupdate'
     command.

TSAM
     Discrete time sampling period  (nonnegative scalar).   TSAM is set
     to 0 for continuous time systems.

YD
     Discrete-time output list (vector)

     indicates which outputs are discrete time (i.e.,     produced by
     D/A converters) and which are continuous time.      yd(ii) = 0 if
     output ii is continuous, = 1 if discrete.

   The remaining variables of the  system data structure are only
present if the corresponding entry of the `sys' vector is true (=1).


File: octave.info,  Node: sysstructtf,  Next: sysstructzp,  Prev: sysstructvars,  Up: sysstruct

30.1.2 `tf' format variables
----------------------------

NUM
     numerator coefficients   (vector)

DEN
     denominator coefficients   (vector)



File: octave.info,  Node: sysstructzp,  Next: sysstructss,  Prev: sysstructtf,  Up: sysstruct

30.1.3 `zp' format variables
----------------------------

ZER
     system zeros   (vector)

POL
     system poles    (vector)

K
     leading coefficient   (scalar)



File: octave.info,  Node: sysstructss,  Prev: sysstructzp,  Up: sysstruct

30.1.4 `ss' format variables
----------------------------

A
B
C
D
     The usual state-space matrices. If a system has both
     continuous and discrete states, they are sorted so that
     continuous states come first, then discrete states

     *Note* some functions (e.g., `bode', `hinfsyn') will not accept
     systems with both discrete and continuous states/outputs

STNAME
     names of system states   (list of strings)



File: octave.info,  Node: sysinterface,  Next: sysdisp,  Prev: sysstruct,  Up: Control Theory

30.2 System Construction and Interface Functions
================================================

Construction and manipulations of the OCST system data structure (*note
sysstruct::) requires attention to many details in order to ensure that
data structure contents remain consistent.  Users are strongly
encouraged to use the system interface functions in this section.
Functions for the formatted display in of system data structures are
given in *Note sysdisp::.

* Menu:

* fir2sys::
* ss2sys::
* tf2sys::
* zp2sys::
* structaccess::
* structintern::


File: octave.info,  Node: fir2sys,  Next: ss2sys,  Up: sysinterface

30.2.1 Finite impulse response system interface functions
---------------------------------------------------------

 -- Function File:  fir2sys (NUM, TSAM, INNAME, OUTNAME)
     construct a system data structure from FIR description

     *Inputs*
    NUM
          vector of coefficients [c0, c1, ..., cn] of the SISO FIR
          transfer function C(z) = c0 + c1*z^(-1) + c2*z^(-2) + ... +
          cn*z^(-n)

    TSAM
          sampling time (default: 1)

    INNAME
          name of input signal;  may be a string or a list with a
          single entry.

    OUTNAME
          name of output signal; may be a string or a list with a
          single entry.

     *Output*
    SYS
          system data structure

     *Example*
          octave:1> sys = fir2sys([1 -1 2 4],0.342,\
          > "A/D input","filter output");
          octave:2> sysout(sys)
          Input(s)
                  1: A/D input

          Output(s):
                  1: filter output (discrete)

          Sampling interval: 0.342
          transfer function form:
          1*z^3 - 1*z^2 + 2*z^1 + 4
          -------------------------
          1*z^3 + 0*z^2 + 0*z^1 + 0

 -- Function File: [C, TSAM, INPUT, OUTPUT] = sys2fir (SYS)
     Extract FIR data from system data structure; see `fir2sys' for
     parameter descriptions.


File: octave.info,  Node: ss2sys,  Next: tf2sys,  Prev: fir2sys,  Up: sysinterface

30.2.2 State space system interface functions
---------------------------------------------

 -- Function File:  ss (A, B, C, D, TSAM, N, NZ, STNAME, INNAME,
          OUTNAME, OUTLIST)
     Create system structure from state-space data.   May be continous,
     discrete, or mixed (sampled data)

     *Inputs*
    A
    B
    C
    D
          usual state space matrices.

          default: D = zero matrix

    TSAM
          sampling rate.  Default: tsam = 0 (continuous system)

    N
    NZ
          number of continuous, discrete states in the system

          If TSAM is 0, n = `rows'(A), nz = 0.

          If TSAM is greater than zero, n = 0, nz = `rows'(A)

          see below for system partitioning

    STNAME
          cell array of strings of state signal names

          default (STNAME=[] on input): `x_n' for continuous states,
          `xd_n' for discrete states

    INNAME
          cell array of strings of input signal names

          default (INNAME = [] on input): `u_n'

    OUTNAME
          cell array of strings of input signal names

          default (OUTNAME = [] on input): `y_n'

    OUTLIST
          list of indices of outputs y that are sampled

          If TSAM is 0, outlist = [].

          If TSAM is greater than 0, outlist = 1:`rows'(C).

     Unlike states, discrete/continous outputs may appear in any order.

     `sys2ss' returns a vector YD where YD(OUTLIST) = 1; all other
     entries of YD are 0.

     *Outputs* OUTSYS = system data structure

     *System partitioning*

     Suppose for simplicity that outlist specified that the first
     several outputs were continuous and the remaining outputs were
     discrete.  Then the system is partitioned as
          x = [ xc ]  (n x 1)
              [ xd ]  (nz x 1 discrete states)
          a = [ acc acd ]  b = [ bc ]
              [ adc add ]      [ bd ]
          c = [ ccc ccd ]  d = [ dc ]
              [ cdc cdd ]      [ dd ]

              (cdc = c(outlist,1:n), etc.)
     with dynamic equations: d/dt xc(t)     = acc*xc(t)      +
     acd*xd(k*tsam) + bc*u(t)

     xd((k+1)*tsam) = adc*xc(k*tsam) + add*xd(k*tsam) + bd*u(k*tsam)

     yc(t)      = ccc*xc(t)      + ccd*xd(k*tsam) + dc*u(t)

     yd(k*tsam) = cdc*xc(k*tsam) + cdd*xd(k*tsam) + dd*u(k*tsam)

     *Signal partitions*
                  | continuous      | discrete               |
          ----------------------------------------------------
          states  | stname(1:n,:)   | stname((n+1):(n+nz),:) |
          ----------------------------------------------------
          outputs | outname(cout,:) | outname(outlist,:)     |
          ----------------------------------------------------
     where cout is the list of in 1:`rows'(P) that are not
     contained in outlist. (Discrete/continuous outputs may be entered
     in any order desired by the user.)

     *Example*
          octave:1> a = [1 2 3; 4 5 6; 7 8 10];
          octave:2> b = [0 0 ; 0 1 ; 1 0];
          octave:3> c = eye (3);
          octave:4> sys = ss (a, b, c, [], 0, 3, 0, {"volts", "amps", "joules"});
          octave:5> sysout(sys);
          Input(s)
                  1: u_1
                  2: u_2

          Output(s):
                  1: y_1
                  2: y_2
                  3: y_3

          state-space form:
          3 continuous states, 0 discrete states
          State(s):
                  1: volts
                  2: amps
                  3: joules

          A matrix: 3 x 3
             1   2   3
             4   5   6
             7   8  10
          B matrix: 3 x 2
            0  0
            0  1
            1  0
          C matrix: 3 x 3
            1  0  0
            0  1  0
            0  0  1
          D matrix: 3 x 3
            0  0
            0  0
            0  0
     Notice that the D matrix is constructed  by default to the correct
     dimensions.  Default input and output signals names were assigned
     since none were given.

 -- Function File: [A, B, C, D, TSAM, N, NZ, STNAME, INNAME, OUTNAME,
YD] = sys2ss (SYS)
     Extract state space representation from system data structure.

     *Input*
    SYS
          System data structure.

     *Outputs*
    A
    B
    C
    D
          State space matrices for SYS.

    TSAM
          Sampling time of SYS (0 if continuous).

    N
    NZ
          Number of continuous, discrete states (discrete states come
          last in state vector X).

    STNAME
    INNAME
    OUTNAME
          Signal names (lists of strings);  names of states, inputs,
          and outputs, respectively.

    YD
          Binary vector; YD(II) is 1 if output Y(II) is discrete
          (sampled); otherwise  YD(II) is 0.

     A warning massage is printed if the system is a mixed continuous
     and discrete system.

     *Example*
          octave:1> sys=tf2sys([1 2],[3 4 5]);
          octave:2> [a,b,c,d] = sys2ss(sys)
          a =
             0.00000   1.00000
            -1.66667  -1.33333
          b =
            0
            1
          c = 0.66667  0.33333
          d = 0


File: octave.info,  Node: tf2sys,  Next: zp2sys,  Prev: ss2sys,  Up: sysinterface

30.2.3 Transfer function system interface functions
---------------------------------------------------

 -- Function File:  tf2sys (NUM, DEN, TSAM, INNAME, OUTNAME)
     Build system data structure from transfer function format data.

     *Inputs*
    NUM
    DEN
          Coefficients of numerator/denominator polynomials.

    TSAM
          Sampling interval; default: 0 (continuous time).

    INNAME
    OUTNAME
          Input/output signal names; may be a string or cell array with
          a single string entry.

     *Output*
    SYS
          System data structure.

     *Example*
          octave:1> sys=tf2sys([2 1],[1 2 1],0.1);
          octave:2> sysout(sys)
          Input(s)
                  1: u_1
          Output(s):
                  1: y_1 (discrete)
          Sampling interval: 0.1
          transfer function form:
          2*z^1 + 1
          -----------------
          1*z^2 + 2*z^1 + 1

 -- Function File: [NUM, DEN, TSAM, INNAME, OUTNAME] = sys2tf (SYS)
     Extract transfer function data from a system data structure.

     See `tf' for parameter descriptions.

     *Example*
          octave:1> sys=ss([1 -2; -1.1,-2.1],[0;1],[1 1]);
          octave:2> [num,den] = sys2tf(sys)
          num = 1.0000  -3.0000
          den = 1.0000   1.1000  -4.3000


File: octave.info,  Node: zp2sys,  Next: structaccess,  Prev: tf2sys,  Up: sysinterface

30.2.4 Zero-pole system interface functions
-------------------------------------------

 -- Function File:  zp2sys (ZER, POL, K, TSAM, INNAME, OUTNAME)
     Create system data structure from zero-pole data.

     *Inputs*
    ZER
          Vector of system zeros.

    POL
          Vector of system poles.

    K
          Scalar leading coefficient.

    TSAM
          Sampling period; default: 0 (continuous system).

    INNAME
    OUTNAME
          Input/output signal names (lists of strings).

     *Output*
    SYS
          System data structure.

     *Example*
          octave:1> sys=zp2sys([1 -1],[-2 -2 0],1);
          octave:2> sysout(sys)
          Input(s)
                  1: u_1
          Output(s):
                  1: y_1
          zero-pole form:
          1 (s - 1) (s + 1)
          -----------------
          s (s + 2) (s + 2)

 -- Function File: [ZER, POL, K, TSAM, INNAME, OUTNAME] = sys2zp (SYS)
     Extract zero/pole/leading coefficient information from a system
     data structure.

     See `zp' for parameter descriptions.

     *Example*
          octave:1> sys=ss([1 -2; -1.1,-2.1],[0;1],[1 1]);
          octave:2> [zer,pol,k] = sys2zp(sys)
          zer = 3.0000
          pol =
            -2.6953
             1.5953
          k = 1


File: octave.info,  Node: structaccess,  Next: structintern,  Prev: zp2sys,  Up: sysinterface

30.2.5 Data structure access functions
--------------------------------------

 -- Function File:  syschnames (SYS, OPT, LIST, NAMES)
     Superseded by `syssetsignals'.

 -- Function File:  syschtsam (SYS, TSAM)
     This function changes the sampling time (tsam) of the system.
     Exits with an error if sys is purely continuous time.

 -- Function File: [N, NZ, M, P, YD] = sysdimensions (SYS, OPT)
     return the number of states, inputs, and/or outputs in the system
     SYS.

     *Inputs*
    SYS
          system data structure

    OPT
          String indicating which dimensions are desired.  Values:
         `"all"'
               (default) return all parameters as specified under
               Outputs below.

         `"cst"'
               return N= number of continuous states

         `"dst"'
               return N= number of discrete states

         `"in"'
               return N= number of inputs

         `"out"'
               return N= number of outputs

     *Outputs*
    N
          number of continuous states (or individual requested
          dimension as specified by OPT).

    NZ
          number of discrete states

    M
          number of system inputs

    P
          number of system outputs

    YD
          binary vector; YD(II) is nonzero if output II is discrete.
          yd(ii) = 0 if output II is continous

 -- Function File: [STNAME, INNAME, OUTNAME, YD] = sysgetsignals (SYS)
 -- Function File: SIGLIST = sysgetsignals (SYS, SIGID)
 -- Function File: SIGNAME = sysgetsignals (SYS, SIGID, SIGNUM, STRFLG)
     Get signal names from a system

     *Inputs*
    SYS
          system data structure for the state space system

    SIGID
          signal id.  String.  Must be one of
         `"in"'
               input signals

         `"out"'
               output signals

         `"st"'
               stage signals

         `"yd"'
               value of logical vector YD

    SIGNUM
          index(indices) or name(s) or signals; see `sysidx'

    STRFLG
          flag to return a string instead of a cell array;  Values:
         `0'
               (default) return a cell array (even if signum specifies
               an individual signal)

         `1'
               return a string.  Exits with an error if signum does not
               specify an individual signal.


     *Outputs*
    *If SIGID is not specified:

         STNAME
         INNAME
         OUTNAME
               signal names (cell array of strings);  names of states,
               inputs, and outputs, respectively.

         YD
               binary vector; YD(II) is nonzero if output II is
               discrete.

    *If SIGID is specified but SIGNUM is not specified:

         `sigid="in"'
               SIGLIST is set to the cell array of input names.

         `sigid="out"'
               SIGLIST is set to the cell array of output names.

         `sigid="st"'
               SIGLIST is set to the cell array of state names.

               stage signals

         `sigid="yd"'
               SIGLIST is set to logical vector indicating discrete
               outputs; SIGLIST(II) = 0 indicates that output II is
               continuous (unsampled), otherwise it is discrete.


    *If the first three input arguments are specified:
          SIGNAME is a cell array of the specified signal names (SIGID
          is `"in"', `"out"', or `"st"'), or else the logical flag
          indicating whether output(s) SIGNUM is(are) discrete
          (SIGVAL=1) or continuous (SIGVAL=0).

     *Examples* (From `sysrepdemo')
          octave> sys=ss(rand(4),rand(4,2),rand(3,4));
          octave># get all signal names
          octave> [Ast,Ain,Aout,Ayd] = sysgetsignals(sys)
          Ast =
          (
            [1] = x_1
            [2] = x_2
            [3] = x_3
            [4] = x_4
          )
          Ain =
          (
            [1] = u_1
            [2] = u_2
          )
          Aout =
          (
            [1] = y_1
            [2] = y_2
            [3] = y_3
          )
          Ayd =

            0  0  0
          octave> # get only input signal names:
          octave> Ain = sysgetsignals(sys,"in")
          Ain =
          (
            [1] = u_1
            [2] = u_2
          )
          octave> # get name of output 2 (in cell array):
          octave> Aout = sysgetsignals(sys,"out",2)
          Aout =
          (
            [1] = y_2
          )
          octave> # get name of output 2 (as string):
          octave> Aout = sysgetsignals(sys,"out",2,1)
          Aout = y_2

 -- Function File:  sysgettype (SYS)
     return the initial system type of the system

     *Input*
    SYS
          System data structure.

     *Output*
    SYSTYPE
          String indicating how the structure was initially
          constructed. Values: `"ss"', `"zp"', or `"tf"'.

     FIR initialized systems return `systype="tf"'.

 -- Function File:  syssetsignals (SYS, OPT, NAMES, SIG_IDX)
     change the names of selected inputs, outputs and states.

     *Inputs*
    SYS
          System data structure.

    OPT
          Change default name (output).

         `"out"'
               Change selected output names.

         `"in"'
               Change selected input names.

         `"st"'
               Change selected state names.

         `"yd"'
               Change selected outputs from discrete to continuous or
               from continuous to discrete.

    NAMES

         `opt = "out", "in", "st"'
               string or string array containing desired signal names
               or values.

         `opt = "yd"'
               To desired output continuous/discrete flag.  Set name to
               0 for continuous, or 1 for discrete.

    SIG_IDX
          indices or names of outputs, yd, inputs, or states whose
          respective names/values should be changed.

          Default: replace entire cell array of names/entire yd vector.

     *Outputs*
    RETSYS
          SYS with appropriate signal names changed (or YD values,
          where appropriate).

     *Example*
          octave:1> sys=ss([1 2; 3 4],[5;6],[7 8]);
          octave:2> sys = syssetsignals(sys,"st",str2mat("Posx","Velx"));
          octave:3> sysout(sys)
          Input(s)
                  1: u_1
          Output(s):
                  1: y_1
          state-space form:
          2 continuous states, 0 discrete states
          State(s):
                  1: Posx
                  2: Velx
          A matrix: 2 x 2
            1  2
            3  4
          B matrix: 2 x 1
            5
            6
          C matrix: 1 x 2
            7  8
          D matrix: 1 x 1
          0

 -- Function File:  sysupdate (SYS, OPT)
     Update the internal representation of a system.

     *Inputs*
    SYS:
          system data structure

    OPT
          string:
         `"tf"'
               update transfer function form

         `"zp"'
               update zero-pole form

         `"ss"'
               update state space form

         `"all"'
               all of the above

     *Outputs*
    RETSYS
          Contains union of data in sys and requested data.  If
          requested data in SYS is already up to date then RETSYS=SYS.

     Conversion to `tf' or `zp' exits with an error if the system is
     mixed continuous/digital.

 -- Function File: [SYSTYPE, NOUT, NIN, NCSTATES, NDSTATES] = minfo
          (INMAT)
     Determines the type of system matrix.  INMAT can be a varying, a
     system, a constant, and an empty matrix.

     *Outputs*
    SYSTYPE
          Can be one of: varying, system, constant, and empty.

    NOUT
          The number of outputs of the system.

    NIN
          The number of inputs of the system.

    NCSTATES
          The number of continuous states of the system.

    NDSTATES
          The number of discrete states of the system.

 -- Function File:  sysgettsam (SYS)
     Return the sampling time of the system SYS.


File: octave.info,  Node: structintern,  Prev: structaccess,  Up: sysinterface

30.2.6 Data structure internal functions
----------------------------------------


File: octave.info,  Node: sysdisp,  Next: blockdiag,  Prev: sysinterface,  Up: Control Theory

30.3 System display functions
=============================

 -- Function File:  sysout (SYS, OPT)
     print out a system data structure in desired format
    SYS
          system data structure

    OPT
          Display option
         `[]'
               primary system form (default)

         `"ss"'
               state space form

         `"tf"'
               transfer function form

         `"zp"'
               zero-pole form

         `"all"'
               all of the above

 -- Function File:  tfout (NUM, DENOM, X)
     Print formatted transfer function n(s)/d(s) to the screen.  X
     defaults to the string `"s"'

 -- Function File:  zpout (ZER, POL, K, X)
     print formatted zero-pole form to the screen.  X defaults to the
     string `"s"'


File: octave.info,  Node: blockdiag,  Next: numerical,  Prev: sysdisp,  Up: Control Theory

30.4 Block Diagram Manipulations
================================

*Note systime::.

   Unless otherwise noted, all parameters (input,output) are system
data structures.

 -- Function File:  bddemo (INPUTS)
     Octave Controls toolbox demo: Block Diagram Manipulations demo.

 -- Function File:  buildssic (CLST, ULST, OLST, ILST, S1, S2, S3, S4,
          S5, S6, S7, S8)
     Form an arbitrary complex (open or closed loop) system in
     state-space form from several systems. `buildssic' can easily
     (despite its cryptic syntax) integrate transfer functions from a
     complex block diagram into a single system with one call.  This
     function is especially useful for building open loop
     interconnections for H-infinity and H-2 designs or for closing
     loops with these controllers.

     Although this function is general purpose, the use of `sysgroup'
     `sysmult', `sysconnect' and the like is recommended for standard
     operations since they can handle mixed discrete and continuous
     systems and also the names of inputs, outputs, and states.

     The parameters consist of 4 lists that describe the connections
     outputs and inputs and up to 8 systems S1-S8.  Format of the lists:
    CLST
          connection list, describes the input signal of each system.
          The maximum number of rows of Clst is equal to the sum of all
          inputs of s1-s8.

          Example: `[1 2 -1; 2 1 0]' means that:  new input 1 is old
          input 1 + output 2 - output 1, and new input 2 is old input 2
          + output 1. The order of rows is arbitrary.

    ULST
          if not empty the old inputs in vector ULST will be appended
          to the outputs. You need this if you want to "pull out" the
          input of a system. Elements are input numbers of S1-S8.

    OLST
          output list, specifiy the outputs of the resulting systems.
          Elements are output numbers of S1-S8.  The numbers are
          allowed to be negative and may appear in any order. An empty
          matrix means all outputs.

    ILST
          input list, specifiy the inputs of the resulting systems.
          Elements are input numbers of S1-S8.  The numbers are allowed
          to be negative and may appear in any order. An empty matrix
          means all inputs.

     Example:  Very simple closed loop system.
          w        e  +-----+   u  +-----+
           --->o--*-->|  K  |--*-->|  G  |--*---> y
               ^  |   +-----+  |   +-----+  |
             - |  |            |            |
               |  |            +----------------> u
               |  |                         |
               |  +-------------------------|---> e
               |                            |
               +----------------------------+

     The closed loop system GW can be optained by
          GW = buildssic([1 2; 2 -1], 2, [1 2 3], 2, G, K);

    CLST
          1st row: connect input 1 (G) with output 2 (K).

          2nd row: connect input 2 (K) with negative output 1 (G).

    ULST
          Append input of 2 (K) to the number of outputs.

    OLST
          Outputs are output of 1 (G), 2 (K) and appended output 3
          (from ULST).

    ILST
          The only input is 2 (K).

     Here is a real example:
                                   +----+
              -------------------->| W1 |---> v1
          z   |                    +----+
          ----|-------------+
              |             |
              |    +---+    v      +----+
              *--->| G |--->O--*-->| W2 |---> v2
              |    +---+       |   +----+
              |                |
              |                v
             u                  y

          min || GW   ||
                   vz   infty

     The closed loop system GW from [z, u]' to [v1, v2, y]' can be
     obtained by (all SISO systems):
          GW = buildssic([1, 4; 2, 4; 3, 1], 3, [2, 3, 5],
                         [3, 4], G, W1, W2, One);
     where "One" is a unity gain (auxillary) function with order 0.
     (e.g. `One = ugain(1);')

 -- Function File: SYS = jet707 ()
     Creates a linearized state-space model of a Boeing 707-321 aircraft
     at V=80 m/s (M = 0.26, GA0 = -3 deg, ALPHA0 = 4 deg, KAPPA = 50
     deg).

     System inputs: (1) thrust and (2) elevator angle.

     System outputs:  (1) airspeed and (2) pitch angle.

     *Reference*: R. Brockhaus: `Flugregelung' (Flight Control),
     Springer, 1994.

 -- Function File:  ord2 (NFREQ, DAMP, GAIN)
     Creates a continuous 2nd order system with parameters:

     *Inputs*
    NFREQ
          natural frequency [Hz]. (not in rad/s)

    DAMP
          damping coefficient

    GAIN
          dc-gain This is steady state value only for damp > 0.  gain
          is assumed to be 1.0 if ommitted.

     *Output*
    OUTSYS
          system data structure has representation with w = 2 * pi *
          nfreq:
                   /                                        \
                   | / -2w*damp -w \  / w \                 |
               G = | |             |, |   |, [ 0  gain ], 0 |
                   | \   w       0 /  \ 0 /                 |
                   \                                        /
*See also* `jet707' (MIMO example, Boeing 707-321
     aircraft model)

 -- Function File:  sysadd (GSYS, HSYS)
     returns SYS = GSYS + HSYS.
        * Exits with an error if GSYS and HSYS are not compatibly
          dimensioned.

        * Prints a warning message is system states have identical
          names; duplicate names are given a suffix to make them unique.

        * SYS input/output names are taken from GSYS.

                    ________
               ----|  gsys  |---
          u   |    ----------  +|
          -----                (_)----> y
              |     ________   +|
               ----|  hsys  |---
                    --------

 -- Function File: SYS = sysappend (SYST, B, C, D, OUTNAME, INNAME, YD)
     appends new inputs and/or outputs to a system

     *Inputs*
    SYST
          system data structure

    B
          matrix to be appended to sys "B" matrix (empty if none)

    C
          matrix to be appended to sys "C" matrix (empty if none)

    D
          revised sys d matrix (can be passed as [] if the revised d is
          all zeros)

    OUTNAME
          list of names for new outputs

    INNAME
          list of names for new inputs

    YD
          binary vector; yd(ii)=0 indicates a continuous output;
          yd(ii)=1 indicates a discrete output.

     *Outputs*
    SYS
                  sys.b := [syst.b , b]
                  sys.c := [syst.c  ]
                           [ c     ]
                  sys.d := [syst.d | D12 ]
                           [ D21   | D22 ]
          where D12, D21, and D22 are the appropriate dimensioned
          blocks of the input parameter D.
             * The leading block D11 of D is ignored.

             * If INNAME and OUTNAME are not given as arguments,
               the new inputs and outputs are be assigned default names.

             * YD is a binary vector of length rows(c) that indicates
                 continuous/sampled outputs.  Default value for YD is:
                  - SYS is continuous or mixed YD = `zeros(1,rows(c))'

                  - SYS is discrete YD = `ones(1,rows(c))'

 -- Function File: CLSYS = sysconnect (SYS, OUT_IDX, IN_IDX, ORDER, TOL)
     Close the loop from specified outputs to respective specified
     inputs

     *Inputs*
    SYS
          System data structure.

    OUT_IDX
    IN_IDX
          Names or indices of signals to connect (see `sysidx').  The
          output specified by out_idx(ii) is connected to the input
          specified by in_idx(ii).

    ORDER
          logical flag (default = 0)
         `0'
               Leave inputs and outputs in their original order.

         `1'
               Permute inputs and outputs to the order shown in the
               diagram below.

    TOL
          Tolerance for singularities in algebraic loops, default:
          200`eps'.

     *Outputs*
    CLSYS
          Resulting closed loop system.

     *Method*

     `sysconnect' internally permutes selected inputs, outputs as shown
     below, closes the loop, and then permutes inputs and outputs back
     to their original order
                           --------------------
           u_1       ----->|                  |----> y_1
                           |        sys       |
                   old u_2 |                  |
          u_2* ---->(+)--->|                  |----->y_2
          (in_idx)   ^     --------------------    | (out_idx)
                     |                             |
                     -------------------------------
     The input that has the summing junction added to it has an *
     added to the end  of the input name.

 -- Function File: [CSYS, ACD, CCD] = syscont (SYS)
     Extract the purely continuous subsystem of an input system.

     *Input*
    SYS
          system data structure.

     *Outputs*
    CSYS
          is the purely continuous input/output connections of SYS

    ACD
    CCD
          connections from discrete states to continuous states,
          discrete states to continuous outputs, respectively.

          returns CSYS empty if no continuous/continous path exists

 -- Function File: [DSYS, ADC, CDC] = sysdisc (SYS)
     *Input*
    SYS
          System data structure.

     *Outputs*
    DSYS
          Purely discrete portion of sys (returned empty if there is no
          purely discrete path from inputs to outputs).

    ADC
    CDC
          Connections from continuous states to discrete states and
          discrete.  outputs, respectively.

 -- Function File: RETSYS = sysdup (ASYS, OUT_IDX, IN_IDX)
     Duplicate specified input/output connections of a system

     *Inputs*
    ASYS
          system data structure

    OUT_IDX
    IN_IDX
          indices or names of desired signals (see `sigidx').
          duplicates are made of `y(out_idx(ii))' and `u(in_idx(ii))'.

     *Output*
    RETSYS
          Resulting closed loop system: duplicated i/o names are
          appended with a `"+"' suffix.

     *Method*

     `sysdup' creates copies of selected inputs and outputs as shown
     below.  U1, Y1 is the set of original inputs/outputs, and U2, Y2
     is the set of duplicated inputs/outputs in the order specified in
     IN_IDX, OUT_IDX, respectively
                    ____________________
          u1  ----->|                  |----> y1
                    |       asys       |
          u2 ------>|                  |----->y2
          (in_idx)  -------------------- (out_idx)

 -- Function File: SYS = sysgroup (ASYS, BSYS)
     Combines two systems into a single system.

     *Inputs*
    ASYS
    BSYS
          System data structures.

     *Output*
    SYS
          sys = block diag(asys,bsys)

                   __________________
                   |    ________    |
          u1 ----->|--> | asys |--->|----> y1
                   |    --------    |
                   |    ________    |
          u2 ----->|--> | bsys |--->|----> y2
                   |    --------    |
                   ------------------
                        Ksys
     The function also rearranges the internal state-space
     realization of SYS so that the continuous states come first and
     the discrete states come last.  If there are duplicate names, the
     second name has a unique suffix appended on to the end of the name.

 -- Function File: SYS = sysmult (ASYS, BSYS)
     Compute sys = Asys*Bsys (series connection):
          u   ----------     ----------
          --->|  Bsys  |---->|  Asys  |--->
              ----------     ----------
     A warning occurs if there is direct feed-through from an input
     or a continuous state of BSYS, through a discrete output of BSYS,
     to a continuous state or output in ASYS (system data structure
     does not recognize discrete inputs).

 -- Function File: RETSYS = sysprune (ASYS, OUT_IDX, IN_IDX)
     Extract specified inputs/outputs from a system

     *Inputs*
    ASYS
          system data structure

    OUT_IDX
    IN_IDX
          Indices or signal names of the outputs and inputs to be kept
          in the returned system; remaining connections are "pruned"
          off.  May select as [] (empty matrix) to specify all
          outputs/inputs.

               retsys = sysprune (Asys, [1:3,4], "u_1");
               retsys = sysprune (Asys, {"tx", "ty", "tz"}, 4);


     *Output*
    RETSYS
          Resulting system.

                     ____________________
          u1 ------->|                  |----> y1
           (in_idx)  |       Asys       | (out_idx)
          u2 ------->|                  |----| y2
            (deleted)-------------------- (deleted)

 -- Function File: PV = sysreorder (VLEN, LIST)
     *Inputs*
    VLEN
          Vector length.

    LIST
          A subset of `[1:vlen]'.

     *Output*
    PV
          A permutation vector to order elements of `[1:vlen]' in
          `list' to the end of a vector.

     Used internally by `sysconnect' to permute vector elements to their
     desired locations.

 -- Function File: RETSYS = sysscale (SYS, OUTSCALE, INSCALE, OUTNAME,
          INNAME)
     scale inputs/outputs of a system.

     *Inputs*
    SYS
          Structured system.

    OUTSCALE
    INSCALE
          Constant matrices of appropriate dimension.

    OUTNAME
    INNAME
          Lists of strings with the names of respectively outputs and
          inputs.

     *Output*
    RETSYS
          resulting open loop system:
                     -----------    -------    -----------
               u --->| inscale |--->| sys |--->| outscale |---> y
                     -----------    -------    -----------
     If the input names and output names (each a list of strings)
     are not given and the scaling matrices are not square, then
     default names will be given to the inputs and/or outputs.

     A warning message is printed if outscale attempts to add continuous
     system outputs to discrete system outputs; otherwise YD is set
     appropriately in the returned value of SYS.

 -- Function File: SYS = syssub (GSYS, HSYS)
     Return sys = Gsys - Hsys.

     *Method*

     GSYS and HSYS are connected in parallel.  The input vector is
     connected to both systems; the outputs are subtracted.  Returned
     system names are those of GSYS.
                   +--------+
              +--->|  Gsys  |---+
              |    +--------+   |
              |                +|
          u --+                (_)--> y
              |                -|
              |    +--------+   |
              +--->|  Hsys  |---+
                   +--------+

 -- Function File:  ugain (N)
     Creates a system with unity gain, no states.  This trivial system
     is sometimes needed to create arbitrary complex systems from
     simple systems with `buildssic'.  Watch out if you are forming
     sampled systems since `ugain' does not contain a sampling period.

 -- Function File: W = wgt1o (VL, VH, FC)
     State space description of a first order weighting function.

     Weighting function are needed by the H-2/H-infinity design
     procedure.  These function are part of the augmented plant P (see
     `hinfdemo' for an application example).

     *Inputs*
    VL
          Gain at low frequencies.

    VH
          Gain at high frequencies.

    FC
          Corner frequency (in Hz, *not* in rad/sec)

     *Output*
    W
          Weighting function, given in form of a system data structure.

 -- Function File: KSYS = parallel (ASYS, BSYS)
     Forms the parallel connection of two systems.

                       --------------------
                       |      --------    |
              u  ----->|----> | asys |--->|----> y1
                  |    |      --------    |
                  |    |      --------    |
                  |--->|----> | bsys |--->|----> y2
                       |      --------    |
                       --------------------
                            ksys

 -- Function File: [RETSYS, NC, NO] = sysmin (SYS, FLG)
     Returns a minimal (or reduced order) system

     *Inputs*
    SYS
          System data structure

    FLG
          When equal to 0 (default value), returns minimal system, in
          which state names are lost; when equal to 1, returns system
          with physical states removed that are either uncontrollable or
          unobservable (cannot reduce further without discarding
          physical meaning of states).
     *Outputs*
    RETSYS
          Returned system.

    NC
          Number of controllable states in the returned system.

    NO
          Number of observable states in the returned system.

    CFLG
          `is_controllable(retsys)'.

    OFLG
          `is_observable(retsys)'.


File: octave.info,  Node: numerical,  Next: sysprop,  Prev: blockdiag,  Up: Control Theory

30.5 Numerical Functions
========================

 -- Function File: X = are (A, B, C, OPT)
     Solve the Algebraic Riccati Equation
          a' * x + x * a - x * b * x + c = 0

     *Inputs* for identically dimensioned square matrices
    A
          N by N matrix;

    B
          N by N matrix or N by M matrix; in the latter case B is
          replaced by b:=b*b';

    C
          N by N matrix or P by M matrix; in the latter case C is
          replaced by c:=c'*c;

    OPT
          (optional argument; default = `"B"'): String option passed to
          `balance' prior to ordered Schur decomposition.

     *Output*
    X
          solution of the ARE.

     *Method* Laub's Schur method (IEEE Transactions on Automatic
     Control, 1979) is applied to the appropriate Hamiltonian matrix.


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


 -- 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 M (N by N) 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.

