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

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

END-INFO-DIR-ENTRY

   Copyright (C) 1996, 1997, 1999, 2000, 2001, 2002, 2005, 2006, 2007,
2011 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: Printing and Saving Plots,  Next: Interacting with Plots,  Prev: Multiple Plot Windows,  Up: High-Level Plotting

15.2.9 Printing and Saving Plots
--------------------------------

The `print' command allows you to save plots in a variety of formats.
For example,

     print -deps foo.eps

writes the current figure to an encapsulated PostScript file called
`foo.eps'.

 -- Function File:  print ()
 -- Function File:  print (OPTIONS)
 -- Function File:  print (FILENAME, OPTIONS)
 -- Function File:  print (H, FILENAME, OPTIONS)
     Print a graph, or save it to a file

     FILENAME defines the file name of the output file.  If the file
     name has no suffix, one is inferred from the specified device and
     appended to the file name.  If no filename is specified, the
     output is sent to the printer.

     H specifies the figure handle.  If no handle is specified the
     handle for the current figure is used.

     OPTIONS:

    `-fH'
          Specify the handle, H, of the figure to be printed.  The
          default is the current figure.

    `-PPRINTER'
          Set the PRINTER name to which the graph is sent if no
          FILENAME is specified.

    `-GGHOSTSCRIPT_COMMAND'
          Specify the command for calling Ghostscript.  For Unix and
          Windows, the defaults are 'gs' and 'gswin32c', respectively.

    `-color'
    `-mono'
          Monochrome or color output.

    `-solid'
    `-dashed'
          Forces all lines to be solid or dashed, respectively.

    `-portrait'
    `-landscape'
          Specify the orientation of the plot for printed output.  For
          non-printed output the aspect ratio of the output corresponds
          to the plot area defined by the "paperposition" property in
          the orientation specified.  This options is equivalent to
          changing the figure's "paperorientation" property.

    `-dDEVICE'
          Output device, where DEVICE is one of:
         `ps'
         `ps2'
         `psc'
         `psc2'
               Postscript (level 1 and 2, mono and color).  The FLTK
               graphics     toolkit generates Postscript level 3.0.

         `eps'
         `eps2'
         `epsc'
         `epsc2'
               Encapsulated postscript (level 1 and 2, mono and color).
               The FLTK graphic toolkit generates Postscript level 3.0.

         `tex'
         `epslatex'
         `epslatexstandalone'
         `pstex'
         `pslatex'
         `pdflatex'
               Generate a LaTeX (or TeX) file for labels, and eps/ps/pdf
               for graphics.  The file produced by `epslatexstandalone'
               can be processed directly by LaTeX.  The other formats
               are intended to be included in a LaTeX (or TeX)
               document.  The `tex' device is the same as the
               `epslatex' device.  The `pdflatex' device is only
               available for the FLTK graphics toolkit.

         `tikz'
               Generate a LaTeX file using PGF/TikZ.  For the FLTK the
               result is   PGF.

         `ill'
         `aifm'
               Adobe Illustrator (Obsolete for Gnuplot versions > 4.2)

         `cdr'
         `corel'
               CorelDraw

         `dxf'
               AutoCAD

         `emf'
         `meta'
               Microsoft Enhanced Metafile

         `fig'
               XFig.  For the Gnuplot graphics toolkit, the additional
               options `-textspecial' or `-textnormal' can be used to
               control     whether the special flag should be set for
               the text in     the figure (default is `-textnormal').

         `hpgl'
               HP plotter language

         `mf'
               Metafont

         `png'
               Portable network graphics

         `jpg'
         `jpeg'
               JPEG image

         `gif'
               GIF image (only available for the Gnuplot graphics
               toolkit)

         `pbm'
               PBMplus

         `svg'
               Scalable vector graphics

         `pdf'
               Portable document format

          If the device is omitted, it is inferred from the file
          extension, or if there is no filename it is sent to the
          printer as postscript.

    `-dGHOSTSCRIPT_DEVICE'
          Additional devices are supported by Ghostscript.  Some
          examples are;

         `ljet2p'
               HP LaserJet IIP

         `ljet3'
               HP LaserJet III

         `deskjet'
               HP DeskJet and DeskJet Plus

         `cdj550'
               HP DeskJet 550C

         `paintjet'
               HP PointJet

         `pcx24b'
               24-bit color PCX file format

         `ppm'
               Portable Pixel Map file format

         `pdfwrite'
               Produces pdf output from eps

          For a complete list, type `system ("gs -h")' to see what
          formats and devices are available.

          When Ghostscript output is sent to a printer the size is
          determined by the figure's "papersize" property.  When the
          output is sent to a file the size is determined by the plot
          box defined by the figure's "paperposition" property.

    `-append'
          Appends the PS, or PDF output to a pre-existing file of the
          same type.

    `-rNUM'
          Resolution of bitmaps in pixels per inch.  For both metafiles
          and SVG the default is the screen resolution, for other it is
          150 dpi.  To specify screen resolution, use "-r0".

    `-tight'
          Forces a tight bounding box for eps-files.

    `-PREVIEW'
          Adds a preview to eps-files.  Supported formats are;

         `-interchange'
               Provides an interchange preview.

         `-metalfile'
               Provides a metafile preview.

         `-pict'
               Provides pict preview.

         `-tiff'
               Provides a tiff preview.

    `-SXSIZE,YSIZE'
          Plot size in pixels for EMF, GIF, JPEG, PBM, PNG and SVG.  For
          PS, EPS, PDF, and other vector formats the plot size is in
          points.  This option is equivalent to changing the size of
          the plot box associated with "paperposition" property.  Using
          the command form of the print function, you must quote the
          XSIZE,YSIZE option.  For example, by writing `"-S640,480"'.

    `-FFONTNAME'
    `-FFONTNAME:SIZE'
    `-F:SIZE'
          Associates all text with the FONTNAME and/or FONTSIZE.
          FONTNAME is ignored for some devices; dxf, fig, hpgl, etc.

     The filename and options can be given in any order.

     Example: Print to a file, using the svg device.

          figure (1)
          clf ()
          surf (peaks)
          print -dsvg figure1.svg

     Example: Print to an HP Deskjet 550C.

          figure (1)
          clf ()
          surf (peaks)
          print -dcdj550

     *See also:* *note figure: doc-figure, *note orient: doc-orient,
     *note saveas: doc-saveas.

 -- Function File:  saveas (H, FILENAME)
 -- Function File:  saveas (H, FILENAME, FMT)
     Save graphic object H to the file FILENAME in graphic format FMT.

     FMT should be one of the following formats:

    `ps'
          Postscript

    `eps'
          Encapsulated Postscript

    `jpg'
          JPEG Image

    `png'
          PNG Image

    `emf'
          Enhanced Meta File

    `pdf'
          Portable Document Format

     All device formats specified in `print' may also be used.  If FMT
     is omitted it is extracted from the extension of FILENAME.  The
     default format is `"pdf"'.

          figure (1);
          clf ();
          surf (peaks);
          saveas(1, "figure1.png");

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

 -- Function File:  orient (ORIENTATION)
     Set the default print orientation.  Valid values for ORIENTATION
     include `"landscape"', `"portrait"', and `"tall"'.

     The `"tall"' option sets the orientation to portait and fills the
     page with the plot, while leaving a 0.25in border.

     If called with no arguments, return the default print orientation.


File: octave.info,  Node: Interacting with Plots,  Next: Test Plotting Functions,  Prev: Printing and Saving Plots,  Up: High-Level Plotting

15.2.10 Interacting with Plots
------------------------------

The user can select points on a plot with the `ginput' function or
selection the position at which to place text on the plot with the
`gtext' function using the mouse.

 -- Function File: [X, Y, BUTTONS] = ginput (N)
     Return which mouse buttons were pressed and keys were hit on the
     current figure.  If N is defined, then wait for N mouse clicks
     before returning.  If N is not defined, then `ginput' will loop
     until the return key is pressed.

 -- Function File: B = waitforbuttonpress ()
     Wait for button or mouse press.over a figure window.  The value of
     B returns 0 if a mouse button was pressed or 1 is a key was
     pressed.

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

 -- Function File:  gtext (S)
 -- Function File:  gtext ({S1; S2; ...})
 -- Function File:  gtext (..., PROP, VAL)
     Place text on the current figure using the mouse.  The text is
     defined by the string S.  If S is a cell array, each element of
     the cell array is written to a separate line.  Additional
     arguments are passed to the underlying text object as properties.

     *See also:* *note ginput: doc-ginput, *note text: doc-text.


File: octave.info,  Node: Test Plotting Functions,  Prev: Interacting with Plots,  Up: High-Level Plotting

15.2.11 Test Plotting Functions
-------------------------------

The functions `sombrero' and `peaks' provide a way to check that
plotting is working.  Typing either `sombrero' or `peaks' at the Octave
prompt should display a three-dimensional plot.

 -- Function File:  sombrero (N)
     Produce the familiar three-dimensional sombrero plot using N grid
     lines.  If N is omitted, a value of 41 is assumed.

     The function plotted is

          z = sin (sqrt (x^2 + y^2)) / (sqrt (x^2 + y^2))

     *See also:* *note surf: doc-surf, *note meshgrid: doc-meshgrid,
     *note mesh: doc-mesh.

 -- Function File:  peaks ()
 -- Function File:  peaks (N)
 -- Function File:  peaks (X, Y)
 -- Function File: Z = peaks (...)
 -- Function File: [X, Y, Z] = peaks (...)
     Generate a function with lots of local maxima and minima.  The
     function has the form

     f(x,y) = 3*(1-x)^2*exp(-x^2 - (y+1)^2) ...
              - 10*(x/5 - x^3 - y^5)*exp(-x^2-y^2) ...
              - 1/3*exp(-(x+1)^2 - y^2)

     Called without a return argument, `peaks' plots the surface of the
     above function using `mesh'.  If N is a scalar, the `peaks'
     returns the values of the above function on a N-by-N mesh over the
     range `[-3,3]'.  The default value for N is 49.

     If N is a vector, then it represents the X and Y values of the
     grid on which to calculate the above function.  The X and Y values
     can be specified separately.

     *See also:* *note surf: doc-surf, *note mesh: doc-mesh, *note
     meshgrid: doc-meshgrid.


File: octave.info,  Node: Graphics Data Structures,  Next: Advanced Plotting,  Prev: High-Level Plotting,  Up: Plotting

15.3 Graphics Data Structures
=============================

* Menu:

* Introduction to Graphics Structures::
* Graphics Objects::
* Graphics Object Properties::
* Searching Properties::
* Managing Default Properties::


File: octave.info,  Node: Introduction to Graphics Structures,  Next: Graphics Objects,  Up: Graphics Data Structures

15.3.1 Introduction to Graphics Structures
------------------------------------------

The graphics functions use pointers, which are of class
graphics_handle, in order to address the data structures which control
graphical displays.  A graphics handle may point any one of a number of
different object types.  The objects are the graphics data structures.
The types of objects are: `figure', `axes', `line', `text', `patch',
`surface', `text' and `image'.

   Each of these objects has a function by the same name. and, each of
these functions returns a graphics handle pointing to an object of
corresponding type.  In addition there are several functions which
operate on properties of the graphics objects and which return handles:
the functions ` plot' and `plot3' return a handle pointing to an object
of type line, the function `subplot' returns a handle pointing to an
object of type axes, the function `fill' returns a handle pointing to
an object of type patch, the functions `area', `bar', `barh', `contour',
`contourf', `contour3', `surf', `mesh', `surfc', `meshc', `errorbar',
`quiver', `quiver3', `scatter', `scatter3', `stair', `stem', `stem3'
each return a handle as documented in *note Data Sources:
doc-datasources.

   The graphics objects are arranged in a hierarchy:

   1. The root is at 0.  i.e., `get (0)' returns the properties of the
root    object.

   2. Below the root are `figure' objects.

   3. Below the `figure' objects are `axes'.

   4. Below the `axes' objects are `line', `text', `patch', `surface',
and `image' objects.

   Graphics handles may be distinguished from function handles (*note
Function Handles::) by means of the function `ishandle'.  `ishandle'
returns true if its argument is a handle of a graphics object.  In
addition, the figure object may be tested using `isfigure'.  `isfigure'
returns true only if its argument is a handle of a figure. ishghandle()
is synonymous with ishandle().  The `whos' function can be used to show
the object type of each currently defined graphics handle.  (Note: this
is not true today, but it is, I hope, considered an error in whos.  It
may be better to have whos just show graphics_handle as the class, and
provide a new function which, given a graphics handle, returns its
object type.  This could generalize the ishandle() functions and, in
fact, replace them.)

   The `get' and `set' commands are used to obtain and set the values
of properties of graphics objects.  In addition, the `get' command may
be used to obtain property names.

   For example, the property "type" of the graphics object pointed to
by the graphics handle h may be displayed by:

     get (h, "type")

   The properties and their current values are returned by `get (h)'
where h is a handle of a graphics object.  If only the names of the
allowed properties are wanted they may be displayed by: `get (h, "")'.

   Thus, for example,

     h = figure ();
     get (h, "type")
     ans = figure
     get (h, "");
     error: get: ambiguous figure property name ; possible matches:

     __graphics_toolkit__  hittest              resize
     __enhanced__          integerhandle        resizefcn
     __modified__          interruptible        selected
     __myhandle__          inverthardcopy       selectionhighlight
     __plot_stream__       keypressfcn          selectiontype
     alphamap              keyreleasefcn        tag
     beingdeleted          menubar              toolbar
     busyaction            mincolormap          type
     buttondownfcn         name                 uicontextmenu
     children              nextplot             units
     clipping              numbertitle          userdata
     closerequestfcn       paperorientation     visible
     color                 paperposition        windowbuttondownfcn
     colormap              paperpositionmode    windowbuttonmotionfcn
     createfcn             papersize            windowbuttonupfcn
     currentaxes           papertype            windowbuttonwheelfcn
     currentcharacter      paperunits           windowstyle
     currentobject         parent               wvisual
     currentpoint          pointer              wvisualmode
     deletefcn             pointershapecdata    xdisplay
     dockcontrols          pointershapehotspot  xvisual
     doublebuffer          position             xvisualmode
     filename              renderer
     handlevisibility      renderermode

   The root figure has index 0.  Its properties may be displayed by:
`get (0, "")'.

   The uses of `get' and `set' are further explained in *note get:
doc-get, *note set: doc-set.

 -- Function File: RES = isprop (H, PROP)
     Return true if PROP is a property of the object with handle H.

     *See also:* *note get: doc-get, *note set: doc-set.


File: octave.info,  Node: Graphics Objects,  Next: Graphics Object Properties,  Prev: Introduction to Graphics Structures,  Up: Graphics Data Structures

15.3.2 Graphics Objects
-----------------------

The hierarchy of graphics objects was explained above.  (See *note
Introduction to Graphics Structures::.  Here the specific objects are
described, and the properties contained in these objects are discussed.
Keep in mind that graphics objects are always referenced by "handle".

root figure
     the top level of the hierarchy and the parent of all figure
     objects.  The `handle' index of the root figure is 0.

figure
     A figure window.

axes
     A set of axes.  This object is a child of a figure object and may
     be a parent of line, text, image, patch, or surface objects.

line
     A line in two or three dimensions.

text
     Text annotations.

image
     A bitmap image.

patch
     A filled polygon, currently limited to two dimensions.

surface
     A three-dimensional surface.

15.3.2.1 Handle Functions
.........................

To determine whether a variable is a graphics object index or a figure
index, use the functions `ishandle' and `isfigure'.

 -- Built-in Function:  ishandle (H)
     Return true if H is a graphics handle and false otherwise.  H may
     also be a matrix of handles in which case a logical array is
     returned that is true where the elements of H are graphics handles
     and false where they are not.

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

 -- Function File:  ishghandle (H)
     Return true if H is a graphics handle and false otherwise.

 -- Function File:  isfigure (H)
     Return true if H is a graphics handle that contains a figure
     object.

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

   The function `gcf' returns an index to the current figure object, or
creates one if none exists.  Similarly, `gca' returns the current axes
object, or creates one (and its parent figure object) if none exists.

 -- Function File:  gcf ()
     Return the current figure handle.  If a figure does not exist,
     create one and return its handle.  The handle may then be used to
     examine or set properties of the figure.  For example,

          fplot (@sin, [-10, 10]);
          fig = gcf ();
          set (fig, "visible", "off");

     plots a sine wave, finds the handle of the current figure, and then
     makes that figure invisible.  Setting the visible property of the
     figure to `"on"' will cause it to be displayed again.

     *See also:* *note get: doc-get, *note set: doc-set.

 -- Function File:  gca ()
     Return a handle to the current axis object.  If no axis object
     exists, create one and return its handle.  The handle may then be
     used to examine or set properties of the axes.  For example,

          ax = gca ();
          set (ax, "position", [0.5, 0.5, 0.5, 0.5]);

     creates an empty axes object, then changes its location and size in
     the figure window.

     *See also:* *note get: doc-get, *note set: doc-set.

   The `get' and `set' functions may be used to examine and set
properties for graphics objects.  For example,

     get (0)
         => ans =
            {
              type = root
              currentfigure = [](0x0)
              children = [](0x0)
              visible = on
              ...
            }

returns a structure containing all the properties of the root figure.
As with all functions in Octave, the structure is returned by value, so
modifying it will not modify the internal root figure plot object.  To
do that, you must use the `set' function.  Also, note that in this
case, the `currentfigure' property is empty, which indicates that there
is no current figure window.

   The `get' function may also be used to find the value of a single
property.  For example,

     get (gca (), "xlim")
         => [ 0 1 ]

returns the range of the x-axis for the current axes object in the
current figure.

   To set graphics object properties, use the set function.  For
example,

     set (gca (), "xlim", [-10, 10]);

sets the range of the x-axis for the current axes object in the current
figure to `[-10, 10]'.  Additionally, calling set with a graphics
object index as the only argument returns a structure containing the
default values for all the properties for the given object type.  For
example,

     set (gca ())

returns a structure containing the default property values for axes
objects.

 -- Built-in Function:  get (H, P)
     Return the named property P from the graphics handle H.  If P is
     omitted, return the complete property list for H.  If H is a
     vector, return a cell array including the property values or lists
     respectively.

 -- Built-in Function:  set (H, PROPERTY, VALUE, ...)
 -- Built-in Function:  set (H, PROPERTIES, VALUES)
 -- Built-in Function:  set (H, PV)
     Set named property values for the graphics handle (or vector of
     graphics handles) H.  There are three ways how to give the
     property names and values:

        * as a comma separated list of PROPERTY, VALUE pairs

          Here, each PROPERTY is a string containing the property name,
          each VALUE is a value of the appropriate type for the
          property.

        * as a cell array of strings PROPERTIES containing property
          names and a cell array VALUES containing property values.

          In this case, the number of columns of VALUES must match the
          number of elements in PROPERTIES.  The first column of VALUES
          contains values for the first entry in PROPERTIES, etc.  The
          number of rows of VALUES must be 1 or match the number of
          elements of H.  In the first case, each handle in H will be
          assigned the same values.  In the latter case, the first
          handle in H will be assigned the values from the first row of
          VALUES and so on.

        * as a structure array PV

          Here, the field names of PV represent the property names, and
          the field values give the property values.  In contrast to
          the previous case, all elements of PV will be set in all
          handles in H independent of the dimensions of PV.

 -- Function File: PARENT = ancestor (H, TYPE)
 -- Function File: PARENT = ancestor (H, TYPE, 'toplevel')
     Return the first ancestor of handle object H whose type matches
     TYPE, where TYPE is a character string.  If TYPE is a cell array
     of strings, return the first parent whose type matches any of the
     given type strings.

     If the handle object H is of type TYPE, return H.

     If `"toplevel"' is given as a 3rd argument, return the highest
     parent in the object hierarchy that matches the condition, instead
     of the first (nearest) one.

     *See also:* *note get: doc-get, *note set: doc-set.

 -- Function File: H = allchild (HANDLES)
     Find all children, including hidden children, of a graphics object.

     This function is similar to `get (h, "children")', but also
     returns hidden objects.  If HANDLES is a scalar, H will be a
     vector.  Otherwise, H will be a cell matrix of the same size as
     HANDLES and each cell will contain a vector of handles.

     *See also:* *note get: doc-get, *note set: doc-set, *note findall:
     doc-findall, *note findobj: doc-findobj.


File: octave.info,  Node: Graphics Object Properties,  Next: Searching Properties,  Prev: Graphics Objects,  Up: Graphics Data Structures

15.3.3 Graphics Object Properties
---------------------------------

* Menu:

* Root Figure Properties::
* Figure Properties::
* Axes Properties::
* Line Properties::
* Text Properties::
* Image Properties::
* Patch Properties::
* Surface Properties::

   In this Section the object properties are discussed in detail,
starting with the root figure properties and continuing through the
graphics object hierarchy.


File: octave.info,  Node: Root Figure Properties,  Next: Figure Properties,  Up: Graphics Object Properties

15.3.3.1 Root Figure Properties
...............................

The `root figure' properties are:
`__modified__'
     -- Values: "on," "off"

`__myhandle__'

`beingdeleted'
     -- Values: "on," "off"

`busyaction'

`buttondownfcn'

`callbackobject'

`children'

`clipping'
     -- Values: "on," "off"

`createfcn'

`currentfigure'

`deletefcn'

`handlevisibility'
     -- Values: "on," "off"

`hittest'
     -- Values: "on," "off"

`interruptible'
     -- Values: "on," "off"

`parent'

`screendepth'

`screenpixelsperinch'

`screensize'

`selected'

`selectionhighlight'

`screendepth'

`screenpixelsperinch'

`showhiddenhandles'
     -- Values: "on," "off"

`tag'

`type'

`uicontextmenu'

`units'

`userdata'

`visible'


File: octave.info,  Node: Figure Properties,  Next: Axes Properties,  Prev: Root Figure Properties,  Up: Graphics Object Properties

15.3.3.2 Figure Properties
..........................

The `figure' properties are:
`__graphics_toolkit__'
     -- The graphics toolkit currently in use.

`__enhanced__'

`__modified__'

`__myhandle__'

`__plot_stream__'

`alphamap'

`beingdeleted'
     -- Values: "on," "off"

`busyaction'

`buttondownfcn'

`children'
     Handle to children.

`clipping'
     -- Values: "on," "off"

`closerequestfcn'
     -- Handle of function to call on close.

`color'

`colormap'
     An N-by-3 matrix containing the color map for the current axes.

`paperorientation'

`createfcn'

`currentaxes'
     Handle to graphics object of current axes.

`currentcharacter'

`currentobject'

`currentpoint'
     Holds the coordinates of the point over which the mouse pointer
     was when the mouse button was pressed.  If a mouse callback
     function is defined, `"currentpoint"' holds the coordinates of the
     point over which the mouse pointer is when the function gets
     called.

`deletefcn'

`dockcontrols'
     -- Values: "on," "off"

`doublebuffer'
     -- Values: "on," "off"

`filename'

`handlevisibility'
     -- Values: "on," "off"

`hittest'

`integerhandle'

`interruptible'
     -- Values: "on," "off"

`inverthardcopy'

`keypressfcn'
     see `"keypressfcn"'

`keyreleasefcn'
     With `"keypressfcn"', The keyboard callback functions.  These
     callback functions get called when a key is pressed/released
     respectively.  The functions are called with two input arguments.
     The first argument holds the handle of the calling figure.  The
     second argument holds the event structure which has the following
     members:
    `Character'
          The ASCII value of the key

    `Key'
          lowercase value of the key

    `Modifier'
          A cell array containing strings representing the modifiers
          pressed with the key.  Possible values are `"shift"',
          `"alt"', and `"control"'.

`menubar'

`mincolormap'

`name'

`nextplot'
     May be one of
    `"new"'

    `"add"'

    `"replace"'

    `"replacechildren"'

`numbertitle'

`paperorientation'
     Indicates the orientation for printing.  Either `"landscape"' or
     `"portrait"'.

`paperposition'

`paperpositionmode'

`papersize'

`papertype'

`paperunits'

`pointer'

`pointershapecdata'

`pointershapehotspot'

`position'

`renderer'

`renderermode'

`resize'

`resizefcn'

`selected'

`selectionhighlight'
     -- Values: "on," "off"

`selectiontype'

`tag'

`toolbar'

`type'

`units'

`userdata'

`visible'
     Either `"on"' or `"off"' to toggle display of the figure.

`windowbuttondownfcn'
     See `"windowbuttonupfcn"'

`windowbuttonmotionfcn'
     See `"windowbuttonupfcn"'

`windowbuttonupfcn'
     With `"windowbuttondownfcn"' and `"windowbuttonmotionfcn"', The
     mouse callback functions.  These callback functions get called when
     the mouse button is pressed, dragged, and released respectively.
     When these callback functions are called, the `"currentpoint"'
     property holds the current coordinates of the cursor.

`windowbuttonwheelfcn'

`windowstyle'

`wvisual'

`wvisualmode'

`xdisplay'

`xvisual'

`xvisualmode'


File: octave.info,  Node: Axes Properties,  Next: Line Properties,  Prev: Figure Properties,  Up: Graphics Object Properties

15.3.3.3 Axes Properties
........................

The `axes' properties are:
`__modified__'

`__myhandle__'

`activepositionproperty'

`alim'

`alimmode'

`ambientlightcolor'

`beingdeleted'

`box'
     Box surrounding axes.  -- Values: "on," "off"

`busyaction'

`buttondownfcn'

`cameraposition'

`camerapositionmode'

`cameratarget'

`cameratargetmode'

`cameraupvector'

`cameraupvectormode'

`cameraviewangle'

`cameraviewanglemode'

`children'

`clim'
     Two-element vector defining the limits for the c axis of an image.
     See `pcolor' property.  Setting this property also forces the
     corresponding mode property to be set to `"manual"'.

`climmode'
     Either `"manual"' or `"auto"'.

`clipping'

`color'

`colororder'

`createfcn'

`currentpoint'
     Holds the coordinates of the point over which the mouse pointer
     was when the mouse button was pressed.  If a mouse callback
     function is defined, `"currentpoint"' holds the coordinates of the
     point over which the mouse pointer is when the function gets
     called.

`dataaspectratio'
     A two-element vector specifying the relative height and width of
     the data displayed in the axes.  Setting `dataaspectratio' to `1,
     2]' causes the length of one unit as displayed on the y-axis to be
     the same as the length of 2 units on the x-axis.  Setting
     `dataaspectratio' also forces the `dataaspectratiomode' property
     to be set to `"manual"'.

`dataaspectratiomode'
     Either `"manual"' or `"auto"'.

`deletefcn'

`drawmode'

`fontangle'

`fontname'

`fontsize'

`fontunits'

`fontweight'

`gridlinestyle'

`handlevisibility'

`hittest'

`interpreter'

`interruptible'

`key'
     Toggle display of the legend.  -- Values: "on," "off" Note that
     this property is not compatible with MATLAB and may be removed in
     a future version of Octave.

`keybox'
     Toggle display of a box around the legend.  -- Values: "on," "off"
     Note that this property is not compatible with MATLAB and may be
     removed in a future version of Octave.

`keypos'
     An integer from 1 to 4 specifying the position of the legend.  1
     indicates upper right corner, 2 indicates upper left, 3 indicates
     lower left, and 4 indicates lower right.  Note that this property
     is not compatible with MATLAB and may be removed in a future
     version of Octave.

`keyreverse'

`layer'

`linestyleorder'

`linewidth'

`minorgridlinestyle'

`nextplot'
     May be one of
    `"new"'

    `"add"'

    `"replace"'

    `"replacechildren"'

`outerposition'
     A vector specifying the position of the plot, including titles,
     axes and legend.  The four elements of the vector are the
     coordinates of the lower left corner and width and height of the
     plot, in units normalized to the width and height of the plot
     window.  For example, `[0.2, 0.3, 0.4, 0.5]' sets the lower left
     corner of the axes at (0.2, 0.3) and the width and height to be
     0.4 and 0.5 respectively.  See also the `position' property.

`parent'

`plotboxaspectratio'

`plotboxaspectratiomode'

`position'
     A vector specifying the position of the plot, excluding titles,
     axes and legend.  The four elements of the vector are the
     coordinates of the lower left corner and width and height of the
     plot, in units normalized to the width and height of the plot
     window.  For example, `[0.2, 0.3, 0.4, 0.5]' sets the lower left
     corner of the axes at (0.2, 0.3) and the width and height to be
     0.4 and 0.5 respectively.  See also the `outerposition' property.

`projection'

`selected'

`selectionhighlight'

`tag'

`tickdir'

`tickdirmode'

`ticklength'

`tightinset'

`title'
     Index of text object for the axes title.

`type'

`uicontextmenu'

`units'

`userdata'

`view'
     A three element vector specifying the view point for
     three-dimensional plots.

`visible'
     Either `"on"' or `"off"' to toggle display of the axes.

`x_normrendertransform'

`x_projectiontransform'

`x_rendertransform'

`x_viewporttransform'

`x_viewtransform'

`xaxislocation'
     Either `"top"' or `"bottom"'.

`xcolor'

`xdir'
     Either `"forward"' or `"reverse"'.

`xgrid'
     Either `"on"' or `"off"' to toggle display of grid lines.

`xlabel'
     Indices to text objects for the axes labels.

`xlim'
     Two-element vector defining the limits for the x-axis.  Setting
     this property also forces the corresponding mode property to be
     set to `"manual"'.

`xlimmode'
     Either `"manual"' or `"auto"'.

`xminorgrid'
     Either `"on"' or `"off"' to toggle display of minor grid lines.

`xminortick'

`xscale'
     Either `"linear"' or `"log"'.

`xtick'
     Set position of tick marks.  Setting this property also forces the
     corresponding mode property to be set to `"manual"'.

`xticklabel'
     Setting this property also forces the corresponding mode property
     to be set to `"manual"'.

`xticklabelmode'
     Either `"manual"' or `"auto"'.

`xtickmode'
     Either `"manual"' or `"auto"'.

`yaxislocation'
     Either `"left"' or `"right"'

`ycolor'

`ydir'
     Either `"forward"' or `"reverse"'.

`ygrid'
     Either `"on"' or `"off"' to toggle display of grid lines.

`ylabel'
     Indices to text objects for the axes labels.

`ylim'
     Two-element vectors defining the limits for the x, y, and z axes
     and the Setting one of these properties also forces the
     corresponding mode property to be set to `"manual"'.

`ylimmode'
     Either `"manual"' or `"auto"'.

`yminorgrid'
     Either `"on"' or `"off"' to toggle display of minor grid lines.

`yminortick'

`yscale'
     Either `"linear"' or `"log"'.

`ytick'
     Set position of tick marks.  Setting this property also forces the
     corresponding mode property to be set to `"manual"'.

`yticklabel'
     Setting this property also forces the corresponding mode property
     to be set to `"manual"'.

`yticklabelmode'
     Either `"manual"' or `"auto"'.

`ytickmode'
     Either `"manual"' or `"auto"'.

`zcolor'

`zdir'
     Either `"forward"' or `"reverse"'.

`zgrid'
     Either `"on"' or `"off"' to toggle display of grid lines.

`zlabel'
     Indices to text objects for the axes labels.

`zlim'
     Two-element vector defining the limits for z-axis.  Setting this
     property also forces the corresponding mode property to be set to
     `"manual"'.

`zlimmode'
     Either `"manual"' or `"auto"'.

`zminorgrid'
     Either `"on"' or `"off"' to toggle display of minor grid lines.

`zminortick'

`zscale'
     Either `"linear"' or `"log"'.

`ztick'
     Set position of tick marks.  Setting this property also forces the
     corresponding mode property to be set to `"manual"'.

`zticklabel'
     Setting this property also forces the corresponding mode property
     to be set to `"manual"'.

`zticklabelmode'
     Either `"manual"' or `"auto"'.

`ztickmode'
     Either `"manual"' or `"auto"'.



File: octave.info,  Node: Line Properties,  Next: Text Properties,  Prev: Axes Properties,  Up: Graphics Object Properties

15.3.3.4 Line Properties
........................

The `line' properties are:
`__modified__'

`__myhandle__'

`beingdeleted'

`busyaction'

`buttondownfcn'

`children'

`clipping'

`color'
     The RGB color of the line, or a color name.  *Note Colors::.

`createfcn'

`deletefcn'

`displayname'

`erasemode'

`handlevisibility'

`hittest'

`interpreter'

`interruptible'

`keylabel'
     The text of the legend entry corresponding to this line.  Note
     that this property is not compatible with MATLAB and may be
     removed in a future version of Octave.

`ldata'
     The lower errorbar in the y direction to be plotted.

`linestyle'
`linewidth'
     *Note Line Styles::.

`linewidth'

`marker'

`markeredgecolor'

`markerfacecolor'

`markersize'
     *Note Marker Styles::.

`parent'

`selected'

`selectionhighlight'

`tag'

`type'

`udata'
     The upper errorbar in the y direction to be plotted.

`uicontextmenu'

`userdata'

`visible'

`xdata'
     The data to be plotted.

`xdatasource'

`xldata'
     The lower errorbar to be plotted.

`xlim'

`xliminclude'

`xudata'
     The upper errorbar to be plotted.

`ydata'
     The data to be plotted.

`ydatasource'

`ylim'

`yliminclude'

`zdata'
     The data to be plotted.

`zdatasource'

`zlim'

`zliminclude'


File: octave.info,  Node: Text Properties,  Next: Image Properties,  Prev: Line Properties,  Up: Graphics Object Properties

15.3.3.5 Text Properties
........................

The `text' properties are:
`__modified__'

`__myhandle__'

`backgroundcolor'

`beingdeleted'

`busyaction'

`buttondownfcn'

`children'

`clipping'

`color'
     The color of the text.  *Note Colors::.

`createfcn'

`deletefcn'

`displayname'

`edgecolor'

`editing'

`erasemode'

`fontangle'
     Flag whether the font is italic or normal.  Valid values are
     'normal', 'italic' and 'oblique'.

`fontname'
     The font used for the text.

`fontsize'
     The size of the font, in points to use.

`fontunits'

`fontweight'
     Flag whether the font is bold, etc.  Valid values are 'normal',
     'bold', 'demi' or 'light'.

`handlevisibility'

`hittest'

`horizontalalignment'
     May be `"left"', `"center"', or `"right"'.

`interpreter'
     Determines how the text is rendered.  Valid values are 'none',
     'tex' or 'latex'.

`interruptible'

`linestyle'

`linewidth'

`margin'

`parent'

`position'
     The coordinates of the text object.

`rotation'
     The angle of rotation for the displayed text, measured in degrees.

`selected'

`selectionhighlight'

`string'
     The character string contained by the text object.

`tag'

`type'

`uicontextmenu'

`units'
     May be `"normalized"' or `"graph"'.

`userdata'

`verticalalignment'

`visible'

`xlim'

`xliminclude'

`ylim'

`yliminclude'

`zlim'

`zliminclude'


File: octave.info,  Node: Image Properties,  Next: Patch Properties,  Prev: Text Properties,  Up: Graphics Object Properties

15.3.3.6 Image Properties
.........................

The `image' properties are:
`__modified__'

`__myhandle__'

`beingdeleted'

`busyaction'

`buttondownfcn'

`cdata'
     The data for the image.  Each pixel of the image corresponds to an
     element of `cdata'.  The value of an element of `cdata' specifies
     the row-index into the colormap of the axes object containing the
     image.  The color value found in the color map for the given index
     determines the color of the pixel.

`cdatamapping'

`children'

`clim'

`climinclude'

`clipping'

`createfcn'

`deletefcn'

`handlevisibility'

`hittest'

`interruptible'

`parent'

`selected'

`selectionhighlight'

`tag'

`type'

`uicontextmenu'

`userdata'

`visible'

`xdata'
     Two-element vector specifying the range of the x-coordinates for
     the image.

`xlim'

`xliminclude'

`ydata'
     Two-element vector specifying the range of the y-coordinates for
     the image.

`ylim'

`yliminclude'


File: octave.info,  Node: Patch Properties,  Next: Surface Properties,  Prev: Image Properties,  Up: Graphics Object Properties

15.3.3.7 Patch Properties
.........................

The `patch' properties are:
`__modified__'

`__myhandle__'

`alim'

`aliminclude'

`alphadatamapping'

`ambientstrength'

`backfacelighting'

`beingdeleted'

`busyaction'

`buttondownfcn'

`cdata'
     Data defining the patch object.

`cdatamapping'

`children'

`clim'

`climinclude'

`clipping'

`createfcn'

`deletefcn'

`diffusestrength'

`edgealpha'

`edgecolor'
     The color of the line defining the patch.  *Note Colors::.

`edgelighting'

`erasemode'

`facealpha'
     A number in the range [0, 1] indicating the transparency of the
     patch.

`facecolor'
     The fill color of the patch.  *Note Colors::.

`facelighting'

`faces'

`facevertexalphadata'

`facevertexcdata'

`handlevisibility'

`hittest'

`interpreter'

`interruptible'

`keylabel'

`linestyle'
     *Note Line Styles::.

`linewidth'
     *Note Line Styles::.

`marker'
     *Note Marker Styles::.

`markeredgecolor'
     *Note Marker Styles::.

`markerfacecolor'
     *Note Marker Styles::.

`markersize'
     *Note Marker Styles::.

`normalmode'

`parent'

`selected'

`selectionhighlight'

`specularcolorreflectance'

`specularexponent'

`specularstrength'

`tag'

`type'

`uicontextmenu'

`userdata'

`vertexnormals'

`vertices'

`visible'

`xdata'
     Data defining the patch object.

`xlim'

`xliminclude'

`ydata'
     Data defining the patch object.

`ylim'

`yliminclude'

`zdata'
     Data defining the patch object.

`zlim'

`zliminclude'


File: octave.info,  Node: Surface Properties,  Prev: Patch Properties,  Up: Graphics Object Properties

15.3.3.8 Surface Properties
...........................

The `surface' properties are:
`__modified__'

`__myhandle__'

`alim'

`aliminclude'

`alphadata'

`alphadatamapping'

`ambientstrength'

`backfacelighting'

`beingdeleted'

`busyaction'

`buttondownfcn'

`cdata'

`cdatamapping'

`cdatasource'

`children'

`clim'

`climinclude'

`clipping'

`createfcn'

`deletefcn'

`diffusestrength'

`edgealpha'

`edgecolor'

`edgelighting'

`erasemode'

`facealpha'

`facecolor'

`facelighting'

`handlevisibility'

`hittest'

`interpreter'

`interruptible'

`keylabel'
     The text of the legend entry corresponding to this surface.  Note
     that this property is not compatible with MATLAB and may be
     removed in a future version of Octave.

`linestyle'

`linewidth'

`marker'

`markeredgecolor'

`markerfacecolor'

`markersize'

`meshstyle'

`normalmode'

`parent'

`selected'

`selectionhighlight'

`specularcolorreflectance'

`specularexponent'

`specularstrength'

`tag'

`type'

`uicontextmenu'

`userdata'

`vertexnormals'

`visible'

`xdata'
     The data determining the surface.  The `xdata' and `ydata'
     elements are vectors and `zdata' must be a matrix.

`xdatasource'

`xlim'

`xliminclude'

`ydata'
     The data determining the surface.  The `xdata' and `ydata'
     elements are vectors and `zdata' must be a matrix.

`ydatasource'

`ylim'

`yliminclude'

`zdata'
     The data determining the surface.  The `xdata' and `ydata'
     elements are vectors and `zdata' must be a matrix.

`zdatasource'

`zlim'

`zliminclude'


File: octave.info,  Node: Searching Properties,  Next: Managing Default Properties,  Prev: Graphics Object Properties,  Up: Graphics Data Structures

15.3.4 Searching Properties
---------------------------

 -- Function File: H = findobj ()
 -- Function File: H = findobj (PROP_NAME, PROP_VALUE)
 -- Function File: H = findobj ('-property', PROP_NAME)
 -- Function File: H = findobj ('-regexp', PROP_NAME, PATTERN)
 -- Function File: H = findobj ('flat', ...)
 -- Function File: H = findobj (H, ...)
 -- Function File: H = findobj (H, '-depth', D, ...)
     Find object with specified property values.  The simplest form is

          findobj (PROP_NAME, PROP_VALUE)

     which returns all of the handles to the objects with the name
     PROP_NAME and the name PROP_VALUE.  The search can be limited to a
     particular object or set of objects and their descendants by
     passing a handle or set of handles H as the first argument to
     `findobj'.

     The depth of hierarchy of objects to which to search to can be
     limited with the '-depth' argument.  To limit the number depth of
     the hierarchy to search to D generations of children, and example
     is

          findobj (H, '-depth', D, PROP_NAME, PROP_VALUE)

     Specifying a depth D of 0, limits the search to the set of object
     passed in H.  A depth D of 0 is equivalent to the '-flat' argument.

     A specified logical operator may be applied to the pairs of
     PROP_NAME and PROP_VALUE.  The supported logical operators are
     '-and', '-or', '-xor', '-not'.

     The objects may also be matched by comparing a regular expression
     to the property values, where property values that match `regexp
     (PROP_VALUE, PATTERN)' are returned.  Finally, objects may be
     matched by property name only, using the '-property' option.

     *See also:* *note get: doc-get, *note set: doc-set.

 -- Function File: H = findall ()
 -- Function File: H = findall (PROP_NAME, PROP_VALUE)
 -- Function File: H = findall (H, ...)
 -- Function File: H = findall (H, "-depth", D, ...)
     Find object with specified property values including hidden
     handles.

     This function performs the same function as `findobj', but it
     includes hidden objects in its search.  For full documentation, see
     `findobj'.

     *See also:* *note get: doc-get, *note set: doc-set, *note findobj:
     doc-findobj, *note allchild: doc-allchild.


File: octave.info,  Node: Managing Default Properties,  Prev: Searching Properties,  Up: Graphics Data Structures

15.3.5 Managing Default Properties
----------------------------------

Object properties have two classes of default values, "factory
defaults" (the initial values) and "user-defined defaults", which may
override the factory defaults.

   Although default values may be set for any object, they are set in
parent objects and apply to child objects.  For example,

     set (0, "defaultlinecolor", "green");

sets the default line color for all objects.  The rule for constructing
the property name to set a default value is

     default + OBJECT-TYPE + PROPERTY-NAME

   This rule can lead to some strange looking names, for example
`defaultlinelinewidth"' specifies the default `linewidth' property for
`line' objects.

   The example above used the root figure object, 0, so the default
property value will apply to all line objects.  However, default values
are hierarchical, so defaults set in a figure objects override those
set in the root figure object.  Likewise, defaults set in axes objects
override those set in figure or root figure objects.  For example,

     subplot (2, 1, 1);
     set (0, "defaultlinecolor", "red");
     set (1, "defaultlinecolor", "green");
     set (gca (), "defaultlinecolor", "blue");
     line (1:10, rand (1, 10));
     subplot (2, 1, 2);
     line (1:10, rand (1, 10));
     figure (2)
     line (1:10, rand (1, 10));

produces two figures.  The line in first subplot window of the first
figure is blue because it inherits its color from its parent axes
object.  The line in the second subplot window of the first figure is
green because it inherits its color from its parent figure object.  The
line in the second figure window is red because it inherits its color
from the global root figure parent object.

   To remove a user-defined default setting, set the default property to
the value `"remove"'.  For example,

     set (gca (), "defaultlinecolor", "remove");

removes the user-defined default line color setting from the current
axes object.  To quickly remove all user-defined defaults use the
`reset' function.

 -- Built-in Function:  reset (H, PROPERTY)
     Remove any defaults set for the handle H.  The default figure
     properties of "position", "units", "windowstyle" and "paperunits"
     and the default axes properties of "position" and "units" are not
     reset.

   Getting the `"default"' property of an object returns a list of
user-defined defaults set for the object.  For example,

     get (gca (), "default");

returns a list of user-defined default values for the current axes
object.

   Factory default values are stored in the root figure object.  The
command

     get (0, "factory");

returns a list of factory defaults.


File: octave.info,  Node: Advanced Plotting,  Prev: Graphics Data Structures,  Up: Plotting

15.4 Advanced Plotting
======================

* Menu:

* Colors::
* Line Styles::
* Marker Styles::
* Callbacks::
* Object Groups::
* Graphics Toolkits::


File: octave.info,  Node: Colors,  Next: Line Styles,  Up: Advanced Plotting

15.4.1 Colors
-------------

Colors may be specified as RGB triplets with values ranging from zero to
one, or by name.  Recognized color names include `"blue"', `"black"',
`"cyan"', `"green"', `"magenta"', `"red"', `"white"', and `"yellow"'.


File: octave.info,  Node: Line Styles,  Next: Marker Styles,  Prev: Colors,  Up: Advanced Plotting

15.4.2 Line Styles
------------------

Line styles are specified by the following properties:

`linestyle'
     May be one of
    `"-"'
          Solid lines.

    `"--"'
          Dashed lines.

    `":"'
          Points.

    `"-."'
          A dash-dot line.

`linewidth'
     A number specifying the width of the line.  The default is 1.  A
     value of 2 is twice as wide as the default, etc.


File: octave.info,  Node: Marker Styles,  Next: Callbacks,  Prev: Line Styles,  Up: Advanced Plotting

15.4.3 Marker Styles
--------------------

Marker styles are specified by the following properties:
`marker'
     A character indicating a plot marker to be place at each data
     point, or `"none"', meaning no markers should be displayed.

`markeredgecolor'
     The color of the edge around the marker, or `"auto"', meaning that
     the edge color is the same as the face color.  *Note Colors::.

`markerfacecolor'
     The color of the marker, or `"none"' to indicate that the marker
     should not be filled.  *Note Colors::.

`markersize'
     A number specifying the size of the marker.  The default is 1.  A
     value of 2 is twice as large as the default, etc.


File: octave.info,  Node: Callbacks,  Next: Object Groups,  Prev: Marker Styles,  Up: Advanced Plotting

15.4.4 Callbacks
----------------

Callback functions can be associated with graphics objects and triggered
after certain events occur.  The basic structure of all callback
function is

     function mycallback (src, data)
     ...
     endfunction

where `src' gives a handle to the source of the callback, and `code'
gives some event specific data.  This can then be associated with an
object either at the objects creation or later with the `set' function.
For example,

     plot (x, "DeleteFcn", @(s, e) disp("Window Deleted"))

where at the moment that the plot is deleted, the message "Window
Deleted" will be displayed.

   Additional user arguments can be passed to callback functions, and
will be passed after the 2 default arguments.  For example:

     plot (x, "DeleteFcn", {@mycallback, "1"})
     ...
     function mycallback (src, data, a1)
       fprintf ("Closing plot %d\n", a1);
     endfunction

   The basic callback functions that are available for all graphics
objects are

   * CreateFcn This is the callback that is called at the moment of the
     objects creation.  It is not called if the object is altered in
     any way, and so it only makes sense to define this callback in the
     function call that defines the object.  Callbacks that are added
     to `CreateFcn' later with the `set' function will never be
     executed.

   * DeleteFcn This is the callback that is called at the moment an
     object is deleted.

   * ButtonDownFcn This is the callback that is called if a mouse
     button is pressed while the pointer is over this object.  Note,
     that the gnuplot interface does not respect this callback.

   The object and figure that the event occurred in that resulted in the
callback being called can be found with the `gcbo' and `gcbf' functions.

 -- Function File: H = gcbo ()
 -- Function File: [H, FIG] = gcbo ()
     Return a handle to the object whose callback is currently
     executing.  If no callback is executing, this function returns the
     empty matrix.  This handle is obtained from the root object
     property "CallbackObject".

     Additionally return the handle of the figure containing the object
     whose callback is currently executing.  If no callback is
     executing, the second output is also set to the empty matrix.

     *See also:* *note gcf: doc-gcf, *note gca: doc-gca, *note gcbf:
     doc-gcbf.

 -- Function File: FIG = gcbf ()
     Return a handle to the figure containing the object whose callback
     is currently executing.  If no callback is executing, this function
     returns the empty matrix.  The handle returned by this function is
     the same as the second output argument of gcbo.

     *See also:* *note gcf: doc-gcf, *note gca: doc-gca, *note gcbo:
     doc-gcbo.

   Callbacks can equally be added to properties with the `addlistener'
function described below.


File: octave.info,  Node: Object Groups,  Next: Graphics Toolkits,  Prev: Callbacks,  Up: Advanced Plotting

15.4.5 Object Groups
--------------------

A number of Octave high level plot functions return groups of other
graphics objects or they return graphics objects that have their
properties linked in such a way that changes to one of the properties
results in changes in the others.  A graphic object that groups other
objects is an `hggroup'

 -- Function File:  hggroup ()
 -- Function File:  hggroup (H)
 -- Function File:  hggroup (..., PROPERTY, VALUE, ...)
     Create group object with parent H.  If no parent is specified, the
     group is created in the current axes.  Return the handle of the
     group object created.

     Multiple property-value pairs may be specified for the group, but
     they must appear in pairs.

   For example a simple use of a `hggroup' might be

     x = 0:0.1:10;
     hg = hggroup ();
     plot (x, sin (x), "color", [1, 0, 0], "parent", hg);
     hold on
     plot (x, cos (x), "color", [0, 1, 0], "parent", hg);
     set (hg, "visible", "off");

which groups the two plots into a single object and controls their
visibility directly.  The default properties of an `hggroup' are the
same as the set of common properties for the other graphics objects.
Additional properties can be added with the `addproperty' function.

 -- Built-in Function:  addproperty (NAME, H, TYPE)
 -- Built-in Function:  addproperty (NAME, H, TYPE, ARG, ...)
     Create a new property named NAME in graphics object H.  TYPE
     determines the type of the property to create.  ARGS usually
     contains the default value of the property, but additional
     arguments might be given, depending on the type of the property.

     The supported property types are:

    `string'
          A string property.  ARG contains the default string value.

    `any'
          An un-typed property.  This kind of property can hold any
          octave value.  ARGS contains the default value.

    `radio'
          A string property with a limited set of accepted values.  The
          first argument must be a string with all accepted values
          separated by a vertical bar ('|').  The default value can be
          marked by enclosing it with a '{' '}' pair.  The default
          value may also be given as an optional second string argument.

    `boolean'
          A boolean property.  This property type is equivalent to a
          radio property with "on|off" as accepted values.  ARG contains
          the default property value.

    `double'
          A scalar double property.  ARG contains the default value.

    `handle'
          A handle property.  This kind of property holds the handle of
          a graphics object.  ARG contains the default handle value.
          When no default value is given, the property is initialized to
          the empty matrix.

    `data'
          A data (matrix) property.  ARG contains the default data
          value.  When no default value is given, the data is
          initialized to the empty matrix.

    `color'
          A color property.  ARG contains the default color value.
          When no default color is given, the property is set to black.
          An optional second string argument may be given to specify an
          additional set of accepted string values (like a radio
          property).

     TYPE may also be the concatenation of a core object type and a
     valid property name for that object type.  The property created
     then has the same characteristics as the referenced property (type,
     possible values, hidden state...).  This allows to clone an
     existing property into the graphics object H.

     Examples:

          addproperty ("my_property", gcf, "string", "a string value");
          addproperty ("my_radio", gcf, "radio", "val_1|val_2|{val_3}");
          addproperty ("my_style", gcf, "linelinestyle", "--");


   Once a property in added to an `hggroup', it is not linked to any
other property of either the children of the group, or any other
graphics object.  Add so to control the way in which this newly added
property is used, the `addlistener' function is used to define a
callback function that is executed when the property is altered.

 -- Built-in Function:  addlistener (H, PROP, FCN)
     Register FCN as listener for the property PROP of the graphics
     object H.  Property listeners are executed (in order of
     registration) when the property is set.  The new value is already
     available when the listeners are executed.

     PROP must be a string naming a valid property in H.

     FCN can be a function handle, a string or a cell array whose first
     element is a function handle.  If FCN is a function handle, the
     corresponding function should accept at least 2 arguments, that
     will be set to the object handle and the empty matrix
     respectively.  If FCN is a string, it must be any valid octave
     expression.  If FCN is a cell array, the first element must be a
     function handle with the same signature as described above.  The
     next elements of the cell array are passed as additional arguments
     to the function.

     Example:

          function my_listener (h, dummy, p1)
            fprintf ("my_listener called with p1=%s\n", p1);
          endfunction

          addlistener (gcf, "position", {@my_listener, "my string"})


 -- Built-in Function:  dellistener (H, PROP, FCN)
     Remove the registration of FCN as a listener for the property PROP
     of the graphics object H.  The function FCN must be the same
     variable (not just the same value), as was passed to the original
     call to `addlistener'.

     If FCN is not defined then all listener functions of PROP are
     removed.

     Example:

          function my_listener (h, dummy, p1)
            fprintf ("my_listener called with p1=%s\n", p1);
          endfunction

          c = {@my_listener, "my string"};
          addlistener (gcf, "position", c);
          dellistener (gcf, "position", c);


   An example of the use of these two functions might be

     x = 0:0.1:10;
     hg = hggroup ();
     h = plot (x, sin (x), "color", [1, 0, 0], "parent", hg);
     addproperty ("linestyle", hg, "linelinestyle", get (h, "linestyle"));
     addlistener (hg, "linestyle", @update_props);
     hold on
     plot (x, cos (x), "color", [0, 1, 0], "parent", hg);

     function update_props (h, d)
       set (get (h, "children"), "linestyle", get (h, "linestyle"));
     endfunction

that adds a `linestyle' property to the `hggroup' and propagating any
changes its value to the children of the group.  The `linkprop'
function can be used to simplify the above to be

     x = 0:0.1:10;
     hg = hggroup ();
     h1 = plot (x, sin (x), "color", [1, 0, 0], "parent", hg);
     addproperty ("linestyle", hg, "linelinestyle", get (h, "linestyle"));
     hold on
     h2 = plot (x, cos (x), "color", [0, 1, 0], "parent", hg);
     hlink = linkprop ([hg, h1, h2], "color");

 -- Function File: HLINK = linkprop (H, PROP)
     Links graphics object properties, such that a change in one is
     propagated to the others.  The properties to link are given as a
     string of cell string array by PROP and the objects containing
     these properties by the handle array H.

     An example of the use of linkprop is

          x = 0:0.1:10;
          subplot (1, 2, 1);
          h1 = plot (x, sin (x));
          subplot (1, 2, 2);
          h2 = plot (x, cos (x));
          hlink = linkprop ([h1, h2], {"color","linestyle"});
          set (h1, "color", "green");
          set (h2, "linestyle", "--");


   These capabilities are used in a number of basic graphics objects.
The `hggroup' objects created by the functions of Octave contain one or
more graphics object and are used to:

   * group together multiple graphics objects,

   * create linked properties between different graphics objects, and

   * to hide the nominal user data, from the actual data of the objects.

For example the `stem' function creates a stem series where each
`hggroup' of the stem series contains two line objects representing the
body and head of the stem.  The `ydata' property of the `hggroup' of
the stem series represents the head of the stem, whereas the body of
the stem is between the baseline and this value.  For example

     h = stem (1:4)
     get (h, "xdata")
     => [  1   2   3   4]'
     get (get (h, "children")(1), "xdata")
     => [  1   1 NaN   2   2 NaN   3   3 NaN   4   4 NaN]'

shows the difference between the `xdata' of the `hggroup' of a stem
series object and the underlying line.

   The basic properties of such group objects is that they consist of
one or more linked `hggroup', and that changes in certain properties of
these groups are propagated to other members of the group.  Whereas,
certain properties of the members of the group only apply to the current
member.

   In addition the members of the group can also be linked to other
graphics objects through callback functions.  For example the baseline
of the `bar' or `stem' functions is a line object, whose length and
position are automatically adjusted, based on changes to the
corresponding hggroup elements.

* Menu:

* Data Sources in Object Groups::
* Area Series::
* Bar Series::
* Contour Groups::
* Error Bar Series::
* Line Series::
* Quiver Group::
* Scatter Group::
* Stair Group::
* Stem Series::
* Surface Group::


File: octave.info,  Node: Data Sources in Object Groups,  Next: Area Series,  Up: Object Groups

15.4.5.1 Data Sources in Object Groups
......................................

All of the group objects contain data source parameters.  There are
string parameters that contain an expression that is evaluated to update
the relevant data property of the group when the `refreshdata' function
is called.

 -- Function File:  refreshdata ()
 -- Function File:  refreshdata (H)
 -- Function File:  refreshdata (H, WORKSPACE)
     Evaluate any `datasource' properties of the current figure and
     update the plot if the corresponding data has changed.  If called
     with one or more arguments H is a scalar or array of figure
     handles to refresh.  The optional second argument WORKSPACE can
     take the following values.

    "base"
          Evaluate the datasource properties in the base workspace.
          (default).

    "caller"
          Evaluate the datasource properties in the workspace of the
          function that called `refreshdata'.

     An example of the use of `refreshdata' is:

          x = 0:0.1:10;
          y = sin (x);
          plot (x, y, "ydatasource", "y");
          for i = 1 : 100
            pause(0.1)
            y = sin (x + 0.1 * i);
            refreshdata();
          endfor


File: octave.info,  Node: Area Series,  Next: Bar Series,  Prev: Data Sources in Object Groups,  Up: Object Groups

15.4.5.2 Area Series
....................

Area series objects are created by the `area' function.  Each of the
`hggroup' elements contains a single patch object.  The properties of
the area series are

`basevalue'
     The value where the base of the area plot is drawn.

`linewidth'
`linestyle'
     The line width and style of the edge of the patch objects making
     up the areas.  *Note Line Styles::.

`edgecolor'
`facecolor'
     The line and fill color of the patch objects making up the areas.
     *Note Colors::.

`xdata'
`ydata'
     The x and y coordinates of the original columns of the data passed
     to `area' prior to the cumulative summation used in the `area'
     function.

`xdatasource'
`ydatasource'
     Data source variables.


File: octave.info,  Node: Bar Series,  Next: Contour Groups,  Prev: Area Series,  Up: Object Groups

15.4.5.3 Bar Series
...................

Bar series objects are created by the `bar' or `barh' functions.  Each
`hggroup' element contains a single patch object.  The properties of
the bar series are

`showbaseline'
`baseline'
`basevalue'
     The property `showbaseline' flags whether the baseline of the bar
     series is displayed (default is "on").  The handle of the graphics
     object representing the baseline is given by the `baseline'
     property and the y-value of the baseline by the `basevalue'
     property.

     Changes to any of these property are propagated to the other
     members of the bar series and to the baseline itself.  Equally
     changes in the properties of the base line itself are propagated
     to the members of the corresponding bar series.

`barwidth'
`barlayout'
`horizontal'
     The property `barwidth' is the width of the bar corresponding to
     the WIDTH variable passed to `bar' or BARH.  Whether the bar
     series is "grouped" or "stacked" is determined by the `barlayout'
     property and whether the bars are horizontal or vertical by the
     `horizontal' property.

     Changes to any of these property are propagated to the other
     members of the bar series.

`linewidth'
`linestyle'
     The line width and style of the edge of the patch objects making
     up the bars.  *Note Line Styles::.

`edgecolor'
`facecolor'
     The line and fill color of the patch objects making up the bars.
     *Note Colors::.

`xdata'
     The nominal x positions of the bars.  Changes in this property and
     propagated to the other members of the bar series.

`ydata'
     The y value of the bars in the `hggroup'.

`xdatasource'
`ydatasource'
     Data source variables.


File: octave.info,  Node: Contour Groups,  Next: Error Bar Series,  Prev: Bar Series,  Up: Object Groups

15.4.5.4 Contour Groups
.......................

Contour group objects are created by the `contour', `contourf' and
`contour3' functions.  The are equally one of the handles returned by
the `surfc' and `meshc' functions.  The properties of the contour group
are

`contourmatrix'
     A read only property that contains the data return by `contourc'
     used to create the contours of the plot.

`fill'
     A radio property that can have the values "on" or "off" that flags
     whether the contours to plot are to be filled.

`zlevelmode'
`zlevel'
     The radio property `zlevelmode' can have the values "none", "auto"
     or "manual".  When its value is "none" there is no z component to
     the plotted contours.  When its value is "auto" the z value of the
     plotted contours is at the same value as the contour itself.  If
     the value is "manual", then the z value at which to plot the
     contour is determined by the `zlevel' property.

`levellistmode'
`levellist'
`levelstepmode'
`levelstep'
     If `levellistmode' is "manual", then the levels at which to plot
     the contours is determined by `levellist'.  If `levellistmode' is
     set to "auto", then the distance between contours is determined by
     `levelstep'.  If both `levellistmode' and `levelstepmode' are set
     to "auto", then there are assumed to be 10 equal spaced contours.

`textlistmode'
`textlist'
`textstepmode'
`textstep'
     If `textlistmode' is "manual", then the labeled contours is
     determined by `textlist'.  If `textlistmode' is set to "auto",
     then the distance between labeled contours is determined by
     `textstep'.  If both `textlistmode' and `textstepmode' are set to
     "auto", then there are assumed to be 10 equal spaced labeled
     contours.

`showtext'
     Flag whether the contour labels are shown or not.

`labelspacing'
     The distance between labels on a single contour in points.

`linewidth'

`linestyle'

`linecolor'
     The properties of the contour lines.  The properties `linewidth'
     and `linestyle' are similar to the corresponding properties for
     lines.  The property `linecolor' is a color property (*note
     Colors::), that can also have the values of "none" or "auto".  If
     `linecolor' is "none", then no contour line is drawn.  If
     `linecolor' is "auto" then the line color is determined by the
     colormap.

`xdata'
`ydata'
`zdata'
     The original x, y, and z data of the contour lines.

`xdatasource'
`ydatasource'
`zdatasource'
     Data source variables.


File: octave.info,  Node: Error Bar Series,  Next: Line Series,  Prev: Contour Groups,  Up: Object Groups

15.4.5.5 Error Bar Series
.........................

Error bar series are created by the `errorbar' function.  Each
`hggroup' element contains two line objects representing the data and
the errorbars separately.  The properties of the error bar series are

`color'
     The RGB color or color name of the line objects of the error bars.
     *Note Colors::.

`linewidth'
`linestyle'
     The line width and style of the line objects of the error bars.
     *Note Line Styles::.

`marker'
`markeredgecolor'
`markerfacecolor'
`markersize'
     The line and fill color of the markers on the error bars.  *Note
     Colors::.

`xdata'
`ydata'
`ldata'
`udata'
`xldata'
`xudata'
     The original x, y, l, u, xl, xu data of the error bars.

`xdatasource'
`ydatasource'
`ldatasource'
`udatasource'
`xldatasource'
`xudatasource'
     Data source variables.


File: octave.info,  Node: Line Series,  Next: Quiver Group,  Prev: Error Bar Series,  Up: Object Groups

15.4.5.6 Line Series
....................

Line series objects are created by the `plot'  and `plot3' functions
and are of the type `line'.  The properties of the line series with the
ability to add data sources.

`color'
     The RGB color or color name of the line objects.  *Note Colors::.

`linewidth'
`linestyle'
     The line width and style of the line objects.  *Note Line Styles::.

`marker'
`markeredgecolor'
`markerfacecolor'
`markersize'
     The line and fill color of the markers.  *Note Colors::.

`xdata'
`ydata'
`zdata'
     The original x, y and z data.

`xdatasource'
`ydatasource'
`zdatasource'
     Data source variables.


File: octave.info,  Node: Quiver Group,  Next: Scatter Group,  Prev: Line Series,  Up: Object Groups

15.4.5.7 Quiver Group
.....................

Quiver series objects are created by the `quiver' or `quiver3'
functions.  Each `hggroup' element of the series contains three line
objects as children representing the body and head of the arrow,
together with a marker as the point of origin of the arrows.  The
properties of the quiver series are

`autoscale'
`autoscalefactor'
     Flag whether the length of the arrows is scaled or defined
     directly from the U, V and W data.  If the arrow length is flagged
     as being scaled by the `autoscale' property, then the length of the
     autoscaled arrow is controlled by the `autoscalefactor'.

`maxheadsize'
     This property controls the size of the head of the arrows in the
     quiver series.  The default value is 0.2.

`showarrowhead'
     Flag whether the arrow heads are displayed in the quiver plot.

`color'
     The RGB color or color name of the line objects of the quiver.
     *Note Colors::.

`linewidth'
`linestyle'
     The line width and style of the line objects of the quiver.  *Note
     Line Styles::.

`marker'
`markerfacecolor'
`markersize'
     The line and fill color of the marker objects at the original of
     the arrows.  *Note Colors::.

`xdata'
`ydata'
`zdata'
     The origins of the values of the vector field.

`udata'
`vdata'
`wdata'
     The values of the vector field to plot.

`xdatasource'
`ydatasource'
`zdatasource'
`udatasource'
`vdatasource'
`wdatasource'
     Data source variables.


File: octave.info,  Node: Scatter Group,  Next: Stair Group,  Prev: Quiver Group,  Up: Object Groups

15.4.5.8 Scatter Group
......................

Scatter series objects are created by the `scatter' or `scatter3'
functions.  A single hggroup element contains as many children as there
are points in the scatter plot, with each child representing one of the
points.  The properties of the stem series are

`linewidth'
     The line width of the line objects of the points.  *Note Line
     Styles::.

`marker'
`markeredgecolor'
`markerfacecolor'
     The line and fill color of the markers of the points.  *Note
     Colors::.

`xdata'
`ydata'
`zdata'
     The original x, y and z data of the stems.

`cdata'
     The color data for the points of the plot.  Each point can have a
     separate color, or a unique color can be specified.

`sizedata'
     The size data for the points of the plot.  Each point can its own
     size or a unique size can be specified.

`xdatasource'
`ydatasource'
`zdatasource'
`cdatasource'
`sizedatasource'
     Data source variables.


File: octave.info,  Node: Stair Group,  Next: Stem Series,  Prev: Scatter Group,  Up: Object Groups

15.4.5.9 Stair Group
....................

Stair series objects are created by the `stair' function.  Each
`hggroup' element of the series contains a single line object as a
child representing the stair.  The properties of the stair series are

`color'
     The RGB color or color name of the line objects of the stairs.
     *Note Colors::.

`linewidth'
`linestyle'
     The line width and style of the line objects of the stairs.  *Note
     Line Styles::.

`marker'
`markeredgecolor'
`markerfacecolor'
`markersize'
     The line and fill color of the markers on the stairs.  *Note
     Colors::.

`xdata'
`ydata'
     The original x and y data of the stairs.

`xdatasource'
`ydatasource'
     Data source variables.


File: octave.info,  Node: Stem Series,  Next: Surface Group,  Prev: Stair Group,  Up: Object Groups

15.4.5.10 Stem Series
.....................

Stem series objects are created by the `stem' or `stem3' functions.
Each `hggroup' element contains a single line object as a child
representing the stems.  The properties of the stem series are

`showbaseline'
`baseline'
`basevalue'
     The property `showbaseline' flags whether the baseline of the stem
     series is displayed (default is "on").  The handle of the graphics
     object representing the baseline is given by the `baseline'
     property and the y-value (or z-value for `stem3') of the baseline
     by the `basevalue' property.

     Changes to any of these property are propagated to the other
     members of the stem series and to the baseline itself.  Equally
     changes in the properties of the base line itself are propagated
     to the members of the corresponding stem series.

`color'
     The RGB color or color name of the line objects of the stems.
     *Note Colors::.

`linewidth'
`linestyle'
     The line width and style of the line objects of the stems.  *Note
     Line Styles::.

`marker'
`markeredgecolor'
`markerfacecolor'
`markersize'
     The line and fill color of the markers on the stems.  *Note
     Colors::.

`xdata'
`ydata'
`zdata'
     The original x, y and z data of the stems.

`xdatasource'
`ydatasource'
`zdatasource'
     Data source variables.


File: octave.info,  Node: Surface Group,  Prev: Stem Series,  Up: Object Groups

15.4.5.11 Surface Group
.......................

Surface group objects are created by the `surf' or `mesh' functions,
but are equally one of the handles returned by the `surfc' or `meshc'
functions.  The surface group is of the type `surface'.

   The properties of the surface group are

`edgecolor'

`facecolor'
     The RGB color or color name of the edges or faces of the surface.
     *Note Colors::.

`linewidth'
`linestyle'
     The line width and style of the lines on the surface.  *Note Line
     Styles::.

`marker'
`markeredgecolor'
`markerfacecolor'
`markersize'
     The line and fill color of the markers on the surface.  *Note
     Colors::.

`xdata'
`ydata'
`zdata'
`cdata'
     The original x, y, z and c data.

`xdatasource'
`ydatasource'
`zdatasource'
`cdatasource'
     Data source variables.


File: octave.info,  Node: Graphics Toolkits,  Prev: Object Groups,  Up: Advanced Plotting

15.4.6 Graphics Toolkits
------------------------

 -- Function File:  graphics_toolkit (NAME)
 -- Function File:  graphics_toolkit (HLIST, NAME)
     Change the default graphics toolkit to NAME.  If the toolkit is
     not already loaded, it is first initialized by calling the
     function `__init_NAME__'.

     When called with a list of figure handles, HLIST, the graphics
     toolkit is changed only for the listed figures.

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

 -- Built-in Function:  available_graphics_toolkits ()
     Return a cell array of registered graphics toolkits.

* Menu:

* Customizing Toolkit Behavior::


File: octave.info,  Node: Customizing Toolkit Behavior,  Up: Graphics Toolkits

15.4.6.1 Customizing Toolkit Behavior
.....................................

The specific behavior of the backend toolkit may be modified using the
following utility functions.  Note: Not all functions apply to every
graphics toolkit.

 -- Loadable Function: [PROG, ARGS] = gnuplot_binary ()
 -- Loadable Function: [OLD_PROG, OLD_ARGS] = gnuplot_binary (NEW_PROG,
          ARG1, ...)
     Query or set the name of the program invoked by the plot command
     when the graphics toolkit is set to "gnuplot".  Additional
     arguments to pass to the external plotting program may also be
     given.  The default value is `"gnuplot"' without additional
     arguments.  *Note Installation::.

 -- Built-in Function: MODE = gui_mode ()
 -- Built-in Function:  gui_mode (MODE)
     Query or set the GUI mode for the current graphics toolkit.  The
     MODE argument can be one of the following strings:
    '2d'
          Allows panning and zooming of current axes.

    '3d'
          Allows rotating and zooming of current axes.

    'none'
          Mouse inputs have no effect.

     This function is currently implemented only for the FLTK graphics
     toolkit.

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

 -- Built-in Function: SPEED = mouse_wheel_zoom ()
 -- Built-in Function:  mouse_wheel_zoom (SPEED)
     Query or set the mouse wheel zoom factor.

     This function is currently implemented only for the FLTK graphics
     toolkit.

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


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

16 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::
* Applying a Function to an Array::
* Special Utility Matrices::
* Famous Matrices::


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

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

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

 -- Built-in Function:  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 non-negative 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 a logical array which is true where the elements of X are
     are infinite and false where they are not.  For example:

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

     *See also:* *note isfinite: doc-isfinite, *note isnan: doc-isnan,
     *note isna: doc-isna.

 -- Mapping Function:  isnan (X)
     Return a logical array which is true where the elements of X are
     NaN values and false where they are not.  NA values are also
     considered NaN values.  For example:

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

     *See also:* *note isna: doc-isna, *note isinf: doc-isinf, *note
     isfinite: doc-isfinite.

 -- Mapping Function:  isfinite (X)
 -- Mapping Function:  finite (X)
     Return a logical array which is true where the elements of X are
     finite values and false where they are not.  For example:

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

     *See also:* *note isinf: doc-isinf, *note isnan: doc-isnan, *note
     isna: doc-isna.

 -- Loadable Function: IDX = find (X)
 -- Loadable Function: IDX = find (X, N)
 -- Loadable Function: IDX = find (X, N, DIRECTION)
 -- Loadable Function: [i, j] = find (...)
 -- Loadable Function: [i, j, v]] = find (...)
     Return a vector of indices of nonzero elements of a matrix, as a
     row if X is a row or as a column otherwise.  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 ]

     If two inputs are given, N indicates the maximum number of
     elements to find from the beginning of the matrix or vector.

     If three inputs are given, DIRECTION should be one of "first" or
     "last", requesting only the first or last N indices, respectively.
     However, the indices are always returned in ascending order.

     Note that this function is particularly useful for sparse
     matrices, as it extracts the non-zero elements as vectors, which
     can then be used to create the original matrix.  For example:

          sz = size(a);
          [i, j, v] = find (a);
          b = sparse(i, j, v, sz(1), sz(2));

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

 -- Loadable Function: IDX = lookup (TABLE, Y, OPT)
     Lookup values in a sorted table.  Usually used as a prelude to
     interpolation.

     If table is increasing and `idx = lookup (table, y)', then
     `table(idx(i)) <= y(i) < table(idx(i+1))' for all `y(i)' within
     the table.  If `y(i) < table (1)' then `idx(i)' is 0. If `y(i) >=
     table(end)' or `isnan (y(i))' then `idx(i)' is `n'.

     If the table is decreasing, then the tests are reversed.  For
     non-strictly monotonic tables, empty intervals are always skipped.
     The result is undefined if TABLE is not monotonic, or if TABLE
     contains a NaN.

     The complexity of the lookup is O(M*log(N)) where N is the size of
     TABLE and M is the size of Y.  In the special case when Y is also
     sorted, the complexity is O(min(M*log(N),M+N)).

     TABLE and Y can also be cell arrays of strings (or Y can be a
     single string).  In this case, string lookup is performed using
     lexicographical comparison.

     If OPTS is specified, it shall be a string with letters indicating
     additional options.

    `m'
          `table(idx(i)) == val(i)' if `val(i)' occurs in table;
          otherwise, `idx(i)' is zero.

    `b'
          `idx(i)' is a logical 1 or 0, indicating whether `val(i)' is
          contained in table or not.

    `l'
          For numeric lookups the leftmost subinterval shall be
          extended to infinity (i.e., all indices at least 1)

    `r'
          For numeric lookups the rightmost subinterval shall be
          extended to infinity (i.e., all indices at most n-1).

 -- 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, ERR 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: Applying a Function to an Array,  Prev: Finding Elements and Checking Conditions,  Up: Matrix Manipulation

16.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 work with 2-D arrays.  To flip N-d arrays
     use `flipdim' instead.

     *See also:* *note flipud: doc-flipud, *note flipdim: doc-flipdim,
     *note rot90: doc-rot90, *note rotdim: doc-rotdim.

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

     *See also:* *note fliplr: doc-fliplr, *note flipdim: doc-flipdim,
     *note rot90: doc-rot90, *note rotdim: doc-rotdim.

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

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

     *See also:* *note fliplr: doc-fliplr, *note flipud: doc-flipud,
     *note rot90: doc-rot90, *note rotdim: doc-rotdim.

 -- Function File:  rot90 (A, K)
     Return a copy of A 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 K 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.

     *See also:* *note rotdim: doc-rotdim, *note flipud: doc-flipud,
     *note fliplr: doc-fliplr, *note flipdim: doc-flipdim.

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

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

     *See also:* *note rot90: doc-rot90, *note flipud: doc-flipud,
     *note fliplr: doc-fliplr, *note flipdim: doc-flipdim.

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

     *See also:* *note horzcat: doc-horzcat, *note vertcat: doc-vertcat.

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

     *See also:* *note cat: doc-cat, *note vertcat: doc-vertcat.

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

     *See also:* *note cat: doc-cat, *note horzcat: doc-horzcat.

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

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

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

          ipermute (permute (a, perm), perm)

     returns the original array A.

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

 -- Built-in Function:  reshape (A, M, N, ...)
 -- Built-in Function:  reshape (A, SIZE)
     Return a matrix with the given dimensions whose elements are taken
     from the matrix A.  The elements of the matrix are accessed 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.

 -- Built-in Function:  resize (X, M)
 -- Built-in Function:  resize (X, M, N)
 -- Built-in Function:  resize (X, M, N, ...)
     Resize X cutting off elements as necessary.

     In the result, element with certain indices is equal to the
     corresponding element of X if the indices are within the bounds of
     X; otherwise, the element is set to zero.

     In other words, the statement

            y = resize (x, dv);

     is equivalent to the following code:

            y = zeros (dv, class (x));
            sz = min (dv, size (x));
            for i = 1:length (sz), idx{i} = 1:sz(i); endfor
            y(idx{:}) = x(idx{:});

     but is performed more efficiently.

     If only M is supplied and it is a scalar, the dimension of the
     result is M-by-M.  If M is a vector, then the dimensions of the
     result are given by the elements of M.  If both M and N are
     scalars, then the dimensions of the result are M-by-N.

     An object can be resized to more dimensions than it has; in such
     case the missing dimensions are assumed to be 1.  Resizing an
     object to fewer dimensions is not possible.

     *See also:* *note reshape: doc-reshape, *note postpad: doc-postpad.

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

     *See also:* permute, ipermute, shiftdim.

 -- 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 positive, the dimensions of X are shifted to the left,
     with the leading dimensions circulated to the end.  If N is
     negative, then the dimensions of X are shifted to the right, with
     N leading 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))
               => [1, 1, 2, 3]
          size (shiftdim (x, 1))
               => [2, 3]
          [b, ns] = shiftdim (x);
               => b =  [1, 1, 1; 1, 1, 1]
               => ns = 1

     *See also:* reshape, permute, ipermute, circshift, squeeze.

 -- 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 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, in which case the dictionary order of the
     strings is used.

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

 -- Function File:  sortrows (A, C)
     Sort the rows of the matrix A according to the order of the
     columns specified in C.  If C is omitted, a lexicographical sort
     is used.  By default ascending order is used however if elements
     of C are negative then the corresponding column is sorted in
     descending order.

 -- Built-in Function:  issorted (A, MODE)
 -- Built-in Function:  issorted (A, `"rows"', MODE)
     Return true if the array is sorted according to MODE, which may be
     either "ascending", "descending", or "either".  By default,  MODE
     is "ascending".  NaNs are treated in the same manner as `sort'.

     If the optional argument "rows" is supplied, check whether the
     array is sorted by rows as output by the function `sortrows' (with
     no options).

     This function does not support sparse matrices.

     *See also:* *note sort: doc-sort, *note sortrows: doc-sortrows.

   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)
 -- Function File:  tril (A, K)
 -- Function File:  tril (A, K, PACK)
 -- Function File:  triu (A)
 -- Function File:  triu (A, K)
 -- Function File:  triu (A, K, PACK)
     Return a new matrix formed by extracting 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.

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

     If the option "pack" is given as third argument, the extracted
     elements are not inserted into a matrix, but rather stacked
     column-wise one above other.

     *See also:* *note triu: doc-triu, *note diag: doc-diag.

 -- Built-in Function:  V = vec (X)
 -- Built-in Function:  V = vec (X, DIM)
     Return the vector obtained by stacking the columns of the matrix X
     one above the other.  Without DIM this is equivalent to `X(:)'.
     If DIM is supplied, the dimensions of V are set to DIM with all
     elements along the last dimension.  This is equivalent to
     `shiftdim (X(:), 1-DIM)'.

 -- 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)
 -- Function File:  prepad (X, L, C)
 -- Function File:  prepad (X, L, C, DIM)
     Prepend 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 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 argument DIM is given, operate along this
     dimension.

     *See also:* *note postpad: doc-postpad, *note cat: doc-cat, *note
     resize: doc-resize.

 -- Function File:  postpad (X, L)
 -- Function File:  postpad (X, L, C)
 -- Function File:  postpad (X, L, C, DIM)
     Append 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 end of X are removed until
     a vector of length L is obtained.

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

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

     *See also:* *note prepad: doc-prepad, *note cat: doc-cat, *note
     resize: doc-resize.

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

     Given a matrix argument, instead of a vector, `diag' extracts the
     K-th diagonal of the matrix.

 -- Function File:  blkdiag (A, B, C, ...)
     Build a block diagonal matrix from A, B, C, ....  All the
     arguments must be numeric and are two-dimensional matrices or
     scalars.

     *See also:* *note diag: doc-diag, *note horzcat: doc-horzcat,
     *note vertcat: doc-vertcat.

   ---------- 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: Applying a Function to an Array,  Next: Special Utility Matrices,  Prev: Rearranging Matrices,  Up: Matrix Manipulation

16.3 Applying a Function to an Array
====================================

 -- Function File:  arrayfun (FUNC, A)
 -- Function File: X = arrayfun (FUNC, A)
 -- Function File: X = arrayfun (FUNC, A, B, ...)
 -- Function File: [X, Y, ...] = arrayfun (FUNC, A, ...)
 -- Function File:  arrayfun (..., "UniformOutput", VAL)
 -- Function File:  arrayfun (..., "ErrorHandler", ERRFUNC)
     Execute a function on each element of an array.  This is useful for
     functions that do not accept array arguments.  If the function does
     accept array arguments it is better to call the function directly.

     The first input argument FUNC can be a string, a function handle,
     an inline function or an anonymous function.  The input argument A
     can be a logic array, a numeric array, a string array, a structure
     array or a cell array.  By a call of the function `arrayfun' all
     elements of A are passed on to the named function FUNC
     individually.

     The named function can also take more than two input arguments,
     with the input arguments given as third input argument B, fourth
     input argument C, ...  If given more than one array input argument
     then all input arguments must have the same sizes, for example:

          arrayfun (@atan2, [1, 0], [0, 1])
          => ans = [1.5708   0.0000]

     If the parameter VAL after a further string input argument
     "UniformOutput" is set `true' (the default), then the named
     function FUNC must return a single element which then will be
     concatenated into the return value and is of type matrix.
     Otherwise, if that parameter is set to `false', then the outputs
     are concatenated in a cell array.  For example:

          arrayfun (@(x,y) x:y, "abc", "def", "UniformOutput", false)
          => ans =
          {
            [1,1] = abcd
            [1,2] = bcde
            [1,3] = cdef
          }

     If more than one output arguments are given then the named function
     must return the number of return values that also are expected, for
     example:

          [A, B, C] = arrayfun (@find, [10; 0], "UniformOutput", false)
          =>
          A =
          {
            [1,1] =  1
            [2,1] = [](0x0)
          }
          B =
          {
            [1,1] =  1
            [2,1] = [](0x0)
          }
          C =
          {
            [1,1] =  10
            [2,1] = [](0x0)
          }

     If the parameter ERRFUNC after a further string input argument
     "ErrorHandler" is another string, a function handle, an inline
     function or an anonymous function, then ERRFUNC defines a function
     to call in the case that FUNC generates an error.  The definition
     of the function must be of the form

          function [...] = errfunc (S, ...)

     where there is an additional input argument to ERRFUNC relative to
     FUNC, given by S.  This is a structure with the elements
     "identifier", "message" and "index", giving respectively the error
     identifier, the error message and the index of the array elements
     that caused the error.  The size of the output argument of ERRFUNC
     must have the same size as the output argument of FUNC, otherwise
     a real error is thrown.  For example:

          function y = ferr (s, x), y = "MyString"; endfunction
          arrayfun (@str2num, [1234], \
                    "UniformOutput", false, "ErrorHandler", @ferr)
          => ans =
          {
           [1,1] = MyString
          }

     *See also:* *note spfun: doc-spfun, *note cellfun: doc-cellfun,
     *note structfun: doc-structfun.

 -- Loadable Function:  bsxfun (F, A, B)
     Apply a binary function F element-by-element to two matrix
     arguments A and B.  The function F must be capable of accepting
     two column-vector arguments of equal length, or one column vector
     argument and a scalar.

     The dimensions of A and B must be equal or singleton.  The
     singleton dimensions of the matrices will be expanded to the same
     dimensionality as the other matrix.

     *See also:* *note arrayfun: doc-arrayfun, *note cellfun:
     doc-cellfun.


File: octave.info,  Node: Special Utility Matrices,  Next: Famous Matrices,  Prev: Applying a Function to an Array,  Up: Matrix Manipulation

16.4 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")

     Calling `eye' with no arguments is equivalent to calling it with
     an argument of 1.  This odd definition is for compatibility with
     MATLAB.

 -- 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.
     If invoked with a single scalar integer argument, return a square
     matrix of the specified size.  If invoked with two or more scalar
     integer arguments, or a vector of integer values, return an array
     with given dimensions.

     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 specifies the class of the return array
     and defaults to double.  For example:

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

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

 -- 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.
     If invoked with a single scalar integer argument, return a square
     matrix of the specified size.  If invoked with two or more scalar
     integer arguments, or a vector of integer values, return an array
     with given dimensions.

     The optional argument CLASS specifies the class of the return array
     and defaults to double.  For example:

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

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

 -- Function File:  repmat (A, M, N)
 -- Function File:  repmat (A, [M N])
 -- Function File:  repmat (A, [M N P ...])
     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.

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

 -- Built-in Function:  repelems (X, R)
     Construct a vector of repeated elements from X.  R is a 2xN
     integer matrix specifying which elements to repeat and how often
     to repeat each element.

     Entries in the first row, R(1,j), select an element to repeat.
     The corresponding entry in the second row, R(2,j), specifies the
     repeat count.  If X is a matrix then the columns of X are imagined
     to be stacked on top of each other for purposes of the selection
     index.  A row vector is always returned.

     Conceptually the result is calculated as follows:

          y = [];
          for i = 1:columns (R)
            y = [y, X(R(1,i)*ones(1, R(2,i)))];
          endfor

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

 -- Loadable Function:  rand (X)
 -- Loadable Function:  rand (N, M)
 -- Loadable Function: V = rand ("state")
 -- Loadable Function:  rand ("state", V)
 -- Loadable Function:  rand ("state", "reset")
 -- Loadable Function: V = rand ("seed")
 -- Loadable Function:  rand ("seed", V)
 -- Loadable Function:  rand ("seed", "reset")
     Return a matrix with random elements uniformly distributed on the
     interval (0, 1).  The arguments are handled the same as the
     arguments for `eye'.

     You can query the state of the random number generator using the
     form

          v = rand ("state")

     This returns a column vector V of length 625.  Later, you can
     restore the random number generator to the state V using the form

          rand ("state", v)

     You may also initialize the state vector from an arbitrary vector
     of length <= 625 for V.  This new state will be a hash based on the
     value of V, not V itself.

     By default, the generator is initialized from `/dev/urandom' if it
     is available, otherwise from CPU time, wall clock time and the
     current fraction of a second.

     To compute the pseudo-random sequence, `rand' uses the Mersenne
     Twister with a period of 2^19937-1 (See M. Matsumoto and T.
     Nishimura, `Mersenne Twister: A 623-dimensionally equidistributed
     uniform pseudorandom number generator', ACM Trans. on Modeling and
     Computer Simulation Vol. 8, No. 1, pp. 3-30, January 1998,
     `http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html').  Do
     *not* use for cryptography without securely hashing several
     returned values together, otherwise the generator state can be
     learned after reading 624 consecutive values.

     Older versions of Octave used a different random number generator.
     The new generator is used by default as it is significantly faster
     than the old generator, and produces random numbers with a
     significantly longer cycle time.  However, in some circumstances
     it might be desirable to obtain the same random sequences as used
     by the old generators.  To do this the keyword "seed" is used to
     specify that the old generators should be use, as in

          rand ("seed", val)

     which sets the seed of the generator to VAL.  The seed of the
     generator can be queried with

          s = rand ("seed")

     However, it should be noted that querying the seed will not cause
     `rand' to use the old generators, only setting the seed will.  To
     cause `rand' to once again use the new generators, the keyword
     "state" should be used to reset the state of the `rand'.

     The state or seed of the generator can be reset to a new random
     value using the "reset" keyword.

     *See also:* *note randn: doc-randn, *note rande: doc-rande, *note
     randg: doc-randg, *note randp: doc-randp.

 -- Function File:  randi (IMAX)
 -- Function File:  randi (IMAX, N)
 -- Function File:  randi (IMAX, M, N, ...)
 -- Function File:  randi ([IMIN, IMAX], ...)
 -- Function File:  randi (..., "CLASS")
     Return random integers in the range 1:IMAX.

     Additional arguments determine the shape of the return matrix.
     When no arguments are specified a single random integer is
     returned.  If one argument N is specified then a square matrix
     (N x N) is returned.  Two or more arguments will return a
     multi-dimensional matrix (M x N x ...).

     The integer range may optionally be described by a two element
     matrix with a lower and upper bound in which case the returned
     integers will be on the interval [IMIN, IMAX].

     The optional argument "CLASS" will return a matrix of the requested
     type.  The default is "double".

     The following example returns 150 integers in the range 1-10.

          ri = randi (10, 150, 1);

     Implementation Note: `randi' relies internally on `rand' which
     uses class "double" to represent numbers.  This limits the maximum
     integer (IMAX) and range (IMAX - IMIN) to the value returned by
     the `bitmax' function.  For IEEE floating point numbers this value
     is `2^53 - 1'.

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

 -- Loadable Function:  randn (X)
 -- Loadable Function:  randn (N, M)
 -- Loadable Function: V = randn ("state")
 -- Loadable Function:  randn ("state", V)
 -- Loadable Function:  randn ("state", "reset")
 -- Loadable Function: V = randn ("seed")
 -- Loadable Function:  randn ("seed", V)
 -- Loadable Function:  randn ("seed", "reset")
     Return a matrix with normally distributed random elements having
     zero mean and variance one.  The arguments are handled the same as
     the arguments for `rand'.

     By default, `randn' uses the Marsaglia and Tsang "Ziggurat
     technique" to transform from a uniform to a normal distribution.

     Reference: G. Marsaglia and W.W. Tsang, `Ziggurat Method for
     Generating Random Variables', J. Statistical Software, vol 5, 2000,
     `http://www.jstatsoft.org/v05/i08/')

     *See also:* *note rand: doc-rand, *note rande: doc-rande, *note
     randg: doc-randg, *note randp: doc-randp.

 -- Loadable Function:  rande (X)
 -- Loadable Function:  rande (N, M)
 -- Loadable Function: V = rande ("state")
 -- Loadable Function:  rande ("state", V)
 -- Loadable Function:  rande ("state", "reset")
 -- Loadable Function: V = rande ("seed")
 -- Loadable Function:  rande ("seed", V)
 -- Loadable Function:  rande ("seed", "reset")
     Return a matrix with exponentially distributed random elements.
     The arguments are handled the same as the arguments for `rand'.

     By default, `randn' uses the Marsaglia and Tsang "Ziggurat
     technique" to transform from a uniform to an exponential
     distribution.

     Reference: G. Marsaglia and W.W. Tsang, `Ziggurat Method for
     Generating Random Variables', J. Statistical Software, vol 5, 2000,
     `http://www.jstatsoft.org/v05/i08/')

     *See also:* *note rand: doc-rand, *note randn: doc-randn, *note
     randg: doc-randg, *note randp: doc-randp.

 -- Loadable Function:  randp (L, X)
 -- Loadable Function:  randp (L, N, M)
 -- Loadable Function: V = randp ("state")
 -- Loadable Function:  randp ("state", V)
 -- Loadable Function:  randp ("state", "reset")
 -- Loadable Function: V = randp ("seed")
 -- Loadable Function:  randp ("seed", V)
 -- Loadable Function:  randp ("seed", "reset")
     Return a matrix with Poisson distributed random elements with mean
     value parameter given by the first argument, L.  The arguments are
     handled the same as the arguments for `rand', except for the
     argument L.

     Five different algorithms are used depending on the range of L and
     whether or not L is a scalar or a matrix.

    For scalar L <= 12, use direct method.
          W.H. Press, et al., `Numerical Recipes in C', Cambridge
          University Press, 1992.

    For scalar L > 12, use rejection method.[1]
          W.H. Press, et al., `Numerical Recipes in C', Cambridge
          University Press, 1992.

    For matrix L <= 10, use inversion method.[2]
          E. Stadlober, et al., WinRand source code, available via FTP.

    For matrix L > 10, use patchwork rejection method.
          E. Stadlober, et al., WinRand source code, available via FTP,
          or H. Zechner, `Efficient sampling from continuous and
          discrete unimodal distributions', Doctoral Dissertation,
          156pp., Technical University Graz, Austria, 1994.

    For L > 1e8, use normal approximation.
          L. Montanet, et al., `Review of Particle Properties',
          Physical Review D 50 p1284, 1994.

     *See also:* *note rand: doc-rand, *note randn: doc-randn, *note
     rande: doc-rande, *note randg: doc-randg.

 -- Loadable Function:  randg (A, X)
 -- Loadable Function:  randg (A, N, M)
 -- Loadable Function: V = randg ("state")
 -- Loadable Function:  randg ("state", V)
 -- Loadable Function:  randg ("state", "reset")
 -- Loadable Function: V = randg ("seed")
 -- Loadable Function:  randg ("seed", V)
 -- Loadable Function:  randg ("seed", "reset")
     Return a matrix with `gamma(A,1)' distributed random elements.
     The arguments are handled the same as the arguments for `rand',
     except for the argument A.

     This can be used to generate many distributions:

    `gamma (a, b)' for `a > -1', `b > 0'
               r = b * randg (a)

    `beta (a, b)' for `a > -1', `b > -1'
               r1 = randg (a, 1)
               r = r1 / (r1 + randg (b, 1))

    `Erlang (a, n)'
               r = a * randg (n)

    `chisq (df)' for `df > 0'
               r = 2 * randg (df / 2)

    `t(df)' for `0 < df < inf' (use randn if df is infinite)
               r = randn () / sqrt (2 * randg (df / 2) / df)

    `F (n1, n2)' for `0 < n1', `0 < n2'
               ## r1 equals 1 if n1 is infinite
               r1 = 2 * randg (n1 / 2) / n1
               ## r2 equals 1 if n2 is infinite
               r2 = 2 * randg (n2 / 2) / n2
               r = r1 / r2

    negative `binomial (n, p)' for `n > 0', `0 < p <= 1'
               r = randp ((1 - p) / p * randg (n))

    non-central `chisq (df, L)', for `df >= 0' and `L > 0'
          (use chisq if `L = 0')

               r = randp (L / 2)
               r(r > 0) = 2 * randg (r(r > 0))
               r(df > 0) += 2 * randg (df(df > 0)/2)

    `Dirichlet (a1, ... ak)'
               r = (randg (a1), ..., randg (ak))
               r = r / sum (r)


     *See also:* *note rand: doc-rand, *note randn: doc-randn, *note
     rande: doc-rande, *note randp: doc-randp.

   The generators operate in the new or old style together, it is not
possible to mix the two.  Initializing any generator with `"state"' or
`"seed"' causes the others to switch to the same style for future calls.

   The state of each generator is independent and calls to different
generators can be interleaved without affecting the final result.  For
example,

     rand ("state", [11, 22, 33]);
     randn ("state", [44, 55, 66]);
     u = rand (100, 1);
     n = randn (100, 1);

and

     rand ("state", [11, 22, 33]);
     randn ("state", [44, 55, 66]);
     u = zeros (100, 1);
     n = zeros (100, 1);
     for i = 1:100
       u(i) = rand ();
       n(i) = randn ();
     end

produce equivalent results.  When the generators are initialized in the
old style with `"seed"' only `rand' and `randn' are independent,
because the old `rande', `randg' and `randp' generators make calls to
`rand' and `randn'.

   The generators are initialized with random states at start-up, so
that the sequences of random numbers are not the same each time you run
Octave.(1) If you really do need to reproduce a sequence of numbers
exactly, you can set the state or seed to a specific value.

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

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

 -- Loadable Function:  randperm (N)
 -- Loadable Function:  randperm (N, M)
     Return a row vector containing a random permutation of `1:N'.  If
     M is supplied, return M permutations, one in each row of an NxM
     matrix.  The complexity is O(M*N) in both time and memory.  The
     randomization is performed using rand().  All permutations are
     equally likely.

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

   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.  If the number of elements is greater than one, then
     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 if both BASE
     and LIMIT are scalars.  If one of them or both are column vectors,
     `linspace' returns a matrix.

     For compatibility with MATLAB, return the second argument if fewer
     than two values are requested.

 -- Function File:  logspace (BASE, LIMIT)
 -- 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.  If N is unspecified it defaults to
     50.

     Also for compatibility with MATLAB, return the second argument if
     fewer than two values are requested.

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

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

   (1) The old versions of `rand' and `randn' obtain their initial
seeds from the system clock.


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

16.5 Famous Matrices
====================

The following functions return famous matrix forms.

 -- Function File:  hadamard (N)
     Construct a Hadamard matrix HN of size N-by-N.  The size N must be
     of the form `2 ^ K * P' in which P is one of 1, 12, 20 or 28.  The
     returned matrix is normalized, meaning `Hn(:,1) == 1' and `Hn(1,:)
     == 1'.

     Some of the properties of Hadamard matrices are:

        * `kron (HM, HN)' is a Hadamard matrix of size M-by-N.

        * `Hn * Hn' == N * eye (N)'.

        * The rows of HN are orthogonal.

        * `det (A) <= abs(det (HN))' for all A with `abs (A (I, J)) <=
          1'.

        * Multiply any row or column by -1 and still have a Hadamard
          matrix.


 -- Function File:  hankel (C)
 -- 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

     *See also:* *note vander: doc-vander, *note sylvester_matrix:
     doc-sylvester_matrix, *note hilb: doc-hilb, *note invhilb:
     doc-invhilb, *note toeplitz: doc-toeplitz.

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

     *See also:* *note hankel: doc-hankel, *note vander: doc-vander,
     *note sylvester_matrix: doc-sylvester_matrix, *note invhilb:
     doc-invhilb, *note toeplitz: doc-toeplitz.

 -- Function File:  invhilb (N)
     Return the inverse of the Hilbert matrix of order N.  This can be
     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', p. 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.

     *See also:* *note hilb: doc-hilb, *note hankel: doc-hankel, *note
     vander: doc-vander, *note sylvester_matrix: doc-sylvester_matrix,
     *note toeplitz: doc-toeplitz.

 -- Function File:  magic (N)
     Create an N-by-N magic square.  Note that `magic (2)' is undefined
     since there is no 2-by-2 magic square.


 -- Function File:  pascal (N)
 -- Function File:  pascal (N, T)
     Return the Pascal matrix of order N if `T = 0'.  T defaults to 0.
     Return lower triangular Cholesky factor of the Pascal matrix if `T
     = 1'.  This matrix is its own inverse, that is `pascal (N, 1) ^ 2
     == eye (N)'.  If `T = -1', return its absolute value.  This is the
     standard Pascal triangle as a lower-triangular matrix.  If `T =
     2', return a transposed and permuted version of `pascal (N, 1)',
     which is the cube-root of the identity matrix.  That is `pascal
     (N, 2) ^ 3 == eye (N)'.

     *See also:* *note hankel: doc-hankel, *note vander: doc-vander,
     *note sylvester_matrix: doc-sylvester_matrix, *note hilb:
     doc-hilb, *note invhilb: doc-invhilb, *note toeplitz:
     doc-toeplitz, *note hadamard: doc-hadamard, *note wilkinson:
     doc-wilkinson, *note compan: doc-compan, *note rosser: doc-rosser.

 -- Function File:  rosser ()
     Return the Rosser matrix.  This is a difficult test case used to
     evaluate eigenvalue algorithms.

     *See also:* *note hankel: doc-hankel, *note vander: doc-vander,
     *note sylvester_matrix: doc-sylvester_matrix, *note hilb:
     doc-hilb, *note invhilb: doc-invhilb, *note toeplitz:
     doc-toeplitz, *note hadamard: doc-hadamard, *note wilkinson:
     doc-wilkinson, *note compan: doc-compan, *note pascal: doc-pascal.

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

     *See also:* *note hankel: doc-hankel, *note vander: doc-vander,
     *note hilb: doc-hilb, *note invhilb: doc-invhilb, *note toeplitz:
     doc-toeplitz.

 -- Function File:  toeplitz (C)
 -- 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)

     *See also:* *note hankel: doc-hankel, *note vander: doc-vander,
     *note sylvester_matrix: doc-sylvester_matrix, *note hilb:
     doc-hilb, *note invhilb: doc-invhilb.

 -- Function File:  vander (C)
 -- Function File:  vander (C, N)
     Return the Vandermonde matrix whose next to last column is C.  If
     N is specified, it determines the number of columns; otherwise, N
     is taken to be equal to the length of 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

     *See also:* *note hankel: doc-hankel, *note sylvester_matrix:
     doc-sylvester_matrix, *note hilb: doc-hilb, *note invhilb:
     doc-invhilb, *note toeplitz: doc-toeplitz.

 -- Function File:  wilkinson (N)
     Return the Wilkinson matrix of order N.  Wilkinson matrices are
     symmetric and tridiagonal with pairs of nearly, but not exactly,
     equal eigenvalues.

     *See also:* *note hankel: doc-hankel, *note vander: doc-vander,
     *note sylvester_matrix: doc-sylvester_matrix, *note hilb:
     doc-hilb, *note invhilb: doc-invhilb, *note toeplitz:
     doc-toeplitz, *note hadamard: doc-hadamard, *note rosser:
     doc-rosser, *note compan: doc-compan, *note pascal: doc-pascal.


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

17 Arithmetic
*************

Unless otherwise noted, all of the functions described in this chapter
will work for real and complex scalar, vector, or matrix arguments.
Functions described as "mapping functions" apply the given operation
individually to each element when given a matrix argument.  For example:

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

* Menu:

* Exponents and Logarithms::
* Complex Arithmetic::
* Trigonometry::
* Sums and Products::
* Utility Functions::
* Special Functions::
* Rational Approximations::
* Coordinate Transformations::
* Mathematical Constants::


File: octave.info,  Node: Exponents and Logarithms,  Next: Complex Arithmetic,  Up: Arithmetic

17.1 Exponents and Logarithms
=============================

 -- Mapping Function:  exp (X)
     Compute `e^x' for each element of X.  To compute the matrix
     exponential, see *note Linear Algebra::.

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

 -- Mapping Function:  expm1 (X)
     Compute `exp (X) - 1' accurately in the neighborhood of zero.

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

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

     *See also:* *note exp: doc-exp, *note log1p: doc-log1p, *note
     log2: doc-log2, *note log10: doc-log10, *note logspace:
     doc-logspace.

 -- Function File:  reallog (X)
     Return the real-valued natural logarithm of each element of X.
     Report an error if any element results in a complex return value.

     *See also:* *note log: doc-log, *note realpow: doc-realpow, *note
     realsqrt: doc-realsqrt.

 -- Mapping Function:  log1p (X)
     Compute `log (1 + X)' accurately in the neighborhood of zero.

     *See also:* *note log: doc-log, *note exp: doc-exp, *note expm1:
     doc-expm1.

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

     *See also:* *note log: doc-log, *note log2: doc-log2, *note
     logspace: doc-logspace, *note exp: doc-exp.

 -- Mapping Function:  log2 (X)
 -- Mapping Function: [F, E] = log2 (X)
     Compute the base-2 logarithm of each element of X.

     If called with two output arguments, split X into binary mantissa
     and exponent so that `1/2 <= abs(f) < 1' and E is an integer.  If
     `x = 0', `f = e = 0'.

     *See also:* *note pow2: doc-pow2, *note log: doc-log, *note log10:
     doc-log10, *note exp: doc-exp.

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

     *See also:* *note log2: doc-log2, *note nextpow2: doc-nextpow2.

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

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

     *See also:* *note pow2: doc-pow2, *note log2: doc-log2.

 -- Function File:  realpow (X, Y)
     Compute the real-valued, element-by-element power operator.  This
     is equivalent to `X .^ Y', except that `realpow' reports an error
     if any return value is complex.

     *See also:* *note reallog: doc-reallog, *note realsqrt:
     doc-realsqrt.

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

     *See also:* *note realsqrt: doc-realsqrt, *note nthroot:
     doc-nthroot.

 -- Function File:  realsqrt (X)
     Return the real-valued square root of each element of X.  Report an
     error if any element results in a complex return value.

     *See also:* *note sqrt: doc-sqrt, *note realpow: doc-realpow,
     *note reallog: doc-reallog.

 -- Mapping Function:  cbrt (X)
     Compute the real cube root of each element of X.  Unlike
     `X^(1/3)', the result will be negative if X is negative.

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

 -- Function File:  nthroot (X, N)
     Compute the n-th root of X, returning real results for real
     components of X.  For example:

          nthroot (-1, 3)
          => -1
          (-1) ^ (1 / 3)
          => 0.50000 - 0.86603i

     N must be a scalar.  If N is not an even integer and X has
     negative entries, an error is produced.

     *See also:* *note realsqrt: doc-realsqrt, *note sqrt: doc-sqrt,
     *note cbrt: doc-cbrt.


File: octave.info,  Node: Complex Arithmetic,  Next: Trigonometry,  Prev: Exponents and Logarithms,  Up: Arithmetic

17.2 Complex Arithmetic
=======================

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 = `atan2 (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.

     *See also:* *note real: doc-real, *note imag: doc-imag.

 -- Function File:  cplxpair (Z)
 -- Function File:  cplxpair (Z, TOL)
 -- Function File:  cplxpair (Z, TOL, DIM)
     Sort the numbers Z into complex conjugate pairs ordered by
     increasing real part.  Place the negative imaginary complex number
     first within each pair.  Place all the real numbers (those with
     `abs (imag (Z) / Z) < TOL)') after the complex pairs.

     If TOL is unspecified the default value is 100*`eps'.

     By default the complex pairs are sorted along the first
     non-singleton dimension of Z.  If DIM is specified, then the
     complex pairs are sorted along this dimension.

     Signal an error if some complex numbers could not be paired.
     Signal an error if all complex numbers are not exact conjugates
     (to within TOL).  Note that there is no defined order for pairs
     with identical real parts but differing imaginary parts.

          cplxpair (exp(2i*pi*[0:4]'/5)) == exp(2i*pi*[3; 2; 4; 1; 0]/5)

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

     *See also:* *note real: doc-real, *note conj: doc-conj.

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

     *See also:* *note imag: doc-imag, *note conj: doc-conj.


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

17.3 Trigonometry
=================

Octave provides the following trigonometric functions where angles are
specified in radians.  To convert from degrees to radians multiply by
`pi/180' (e.g., `sin (30 * pi/180)' returns the sine of 30 degrees).  As
an alternative, Octave provides a number of trigonometric functions
which work directly on an argument specified in degrees.  These
functions are named after the base trigonometric function with a `d'
suffix.  For example, `sin' expects an angle in radians while `sind'
expects an angle in degrees.

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

     *See also:* *note asin: doc-asin, *note sind: doc-sind, *note
     sinh: doc-sinh.

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

     *See also:* *note acos: doc-acos, *note cosd: doc-cosd, *note
     cosh: doc-cosh.

 -- Mapping Function:  tan (Z)
     Compute the tangent for each element of X in radians.

     *See also:* *note atan: doc-atan, *note tand: doc-tand, *note
     tanh: doc-tanh.

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

     *See also:* *note asec: doc-asec, *note secd: doc-secd, *note
     sech: doc-sech.

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

     *See also:* *note acsc: doc-acsc, *note cscd: doc-cscd, *note
     csch: doc-csch.

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

     *See also:* *note acot: doc-acot, *note cotd: doc-cotd, *note
     coth: doc-coth.

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

     *See also:* *note sin: doc-sin, *note asind: doc-asind.

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

     *See also:* *note cos: doc-cos, *note acosd: doc-acosd.

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

     *See also:* *note tan: doc-tan, *note atand: doc-atand.

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

     *See also:* *note sec: doc-sec, *note asecd: doc-asecd.

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

     *See also:* *note csc: doc-csc, *note acscd: doc-acscd.

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

     *See also:* *note cot: doc-cot, *note acotd: doc-acotd.

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

     *See also:* *note asinh: doc-asinh, *note cosh: doc-cosh, *note
     tanh: doc-tanh.

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

     *See also:* *note acosh: doc-acosh, *note sinh: doc-sinh, *note
     tanh: doc-tanh.

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

     *See also:* *note atanh: doc-atanh, *note sinh: doc-sinh, *note
     cosh: doc-cosh.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

 -- Mapping Function:  atan2 (Y, X)
     Compute atan (Y / X) for corresponding elements of Y and X.
     Signal an error if Y and X do not match in size and orientation.

   Octave provides the following trigonometric functions where angles
are specified in degrees.  These functions produce true zeros at the
appropriate intervals rather than the small round-off error that occurs
when using radians.  For example:

     cosd (90)
          => 0
     cos (pi/2)
          => 6.1230e-17

 -- Function File:  sind (X)
     Compute the sine for each element of X in degrees.  Returns zero
     for elements where `X/180' is an integer.

     *See also:* *note asind: doc-asind, *note sin: doc-sin.

 -- Function File:  cosd (X)
     Compute the cosine for each element of X in degrees.  Returns zero
     for elements where `(X-90)/180' is an integer.

     *See also:* *note acosd: doc-acosd, *note cos: doc-cos.

 -- Function File:  tand (X)
     Compute the tangent for each element of X in degrees.  Returns zero
     for elements where `X/180' is an integer and `Inf' for elements
     where `(X-90)/180' is an integer.

     *See also:* *note atand: doc-atand, *note tan: doc-tan.

 -- Function File:  secd (X)
     Compute the secant for each element of X in degrees.

     *See also:* *note asecd: doc-asecd, *note sec: doc-sec.

 -- Function File:  cscd (X)
     Compute the cosecant for each element of X in degrees.

     *See also:* *note acscd: doc-acscd, *note csc: doc-csc.

 -- Function File:  cotd (X)
     Compute the cotangent for each element of X in degrees.

     *See also:* *note acotd: doc-acotd, *note cot: doc-cot.

 -- Function File:  asind (X)
     Compute the inverse sine in degrees for each element of X.

     *See also:* *note sind: doc-sind, *note asin: doc-asin.

 -- Function File:  acosd (X)
     Compute the inverse cosine in degrees for each element of X.

     *See also:* *note cosd: doc-cosd, *note acos: doc-acos.

 -- Function File:  atand (X)
     Compute the inverse tangent in degrees for each element of X.

     *See also:* *note tand: doc-tand, *note atan: doc-atan.

 -- Function File:  asecd (X)
     Compute the inverse secant in degrees for each element of X.

     *See also:* *note secd: doc-secd, *note asec: doc-asec.

 -- Function File:  acscd (X)
     Compute the inverse cosecant in degrees for each element of X.

     *See also:* *note cscd: doc-cscd, *note acsc: doc-acsc.

 -- Function File:  acotd (X)
     Compute the inverse cotangent in degrees for each element of X.

     *See also:* *note cotd: doc-cotd, *note acot: doc-acot.


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

17.4 Sums and Products
======================

 -- Built-in Function:  sum (X)
 -- Built-in Function:  sum (X, DIM)
 -- Built-in Function:  sum (..., 'native')
 -- Built-in Function:  sum (..., 'double')
 -- Built-in Function:  sum (..., 'extra')
     Sum of elements along dimension DIM.  If DIM is omitted, it
     defaults to the first non-singleton dimension.

     If the optional argument 'native' is given, then the sum is
     performed in the same type as the original argument, rather than
     in the default double type.  For example:

          sum ([true, true])
            => 2
          sum ([true, true], 'native')
            => true

     On the contrary, if 'double' is given, the sum is performed in
     double precision even for single precision inputs.

     For double precision inputs, 'extra' indicates that a more
     accurate algorithm than straightforward summation is to be used.
     For single precision inputs, 'extra' is the same as 'double'.
     Otherwise, 'extra' has no effect.

     *See also:* *note cumsum: doc-cumsum, *note sumsq: doc-sumsq,
     *note prod: doc-prod.

 -- Built-in Function:  prod (X)
 -- Built-in Function:  prod (X, DIM)
     Product of elements along dimension DIM.  If DIM is omitted, it
     defaults to the first non-singleton dimension.

     *See also:* *note cumprod: doc-cumprod, *note sum: doc-sum.

 -- Built-in Function:  cumsum (X)
 -- Built-in Function:  cumsum (X, DIM)
 -- Built-in Function:  cumsum (..., 'native')
     Cumulative sum of elements along dimension DIM.  If DIM is
     omitted, it defaults to the first non-singleton dimension.

     The "native" argument implies the summation is performed in native
     type.   See `sum' for a complete description and example of the
     use of "native".

     *See also:* *note sum: doc-sum, *note cumprod: doc-cumprod.

 -- Built-in Function:  cumprod (X)
 -- Built-in Function:  cumprod (X, DIM)
     Cumulative product of elements along dimension DIM.  If DIM is
     omitted, it defaults to the first non-singleton dimension.

     *See also:* *note prod: doc-prod, *note cumsum: doc-cumsum.

 -- Built-in Function:  sumsq (X)
 -- Built-in Function:  sumsq (X, DIM)
     Sum of squares of elements along dimension DIM.  If DIM is
     omitted, it defaults to the first non-singleton dimension.

     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.

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

 -- Function File:  accumarray (SUBS, VALS, SZ, FUNC, FILLVAL, ISSPARSE)
 -- Function File:  accumarray (CSUBS, VALS, ...)
     Create an array by accumulating the elements of a vector into the
     positions defined by their subscripts.  The subscripts are defined
     by the rows of the matrix SUBS and the values by VALS.  Each row
     of SUBS corresponds to one of the values in VALS.

     The size of the matrix will be determined by the subscripts
     themselves.  However, if SZ is defined it determines the matrix
     size.  The length of SZ must correspond to the number of columns
     in SUBS.

     The default action of `accumarray' is to sum the elements with the
     same subscripts.  This behavior can be modified by defining the
     FUNC function.  This should be a function or function handle that
     accepts a column vector and returns a scalar.  The result of the
     function should not depend on the order of the subscripts.

     The elements of the returned array that have no subscripts
     associated with them are set to zero.  Defining FILLVAL to some
     other value allows these values to be defined.

     By default `accumarray' returns a full matrix.  If ISSPARSE is
     logically true, then a sparse matrix is returned instead.

     An example of the use of `accumarray' is:

          accumarray ([1,1,1;2,1,2;2,3,2;2,1,2;2,3,2], 101:105)
          => ans(:,:,1) = [101, 0, 0; 0, 0, 0]
             ans(:,:,2) = [0, 0, 0; 206, 0, 208]

     The complexity in the non-sparse case is generally O(M+N), where N
     is the number of subscripts and M is the maximum subscript
     (linearized in multi-dimensional case).  If FUNC is one of `@sum'
     (default), `@max', `@min' or `@(x) {x}', an optimized code path is
     used.  Note that for general reduction function the interpreter
     overhead can play a major part and it may be more efficient to do
     multiple accumarray calls and compute the results in a vectorized
     manner.

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

 -- Function File:  accumdim (SUBS, VALS, DIM, N, FUNC, FILLVAL)
     Create an array by accumulating the slices of an array into the
     positions defined by their subscripts along a specified dimension.
     The subscripts are defined by the index vector SUBS.  The
     dimension is specified by DIM.  If not given, it defaults to the
     first non-singleton dimension.

     The extent of the result matrix in the working dimension will be
     determined by the subscripts themselves.  However, if N is defined
     it determines this extent.

     The default action of `accumdim' is to sum the subarrays with the
     same subscripts.  This behavior can be modified by defining the
     FUNC function.  This should be a function or function handle that
     accepts an array and a dimension, and reduces the array along this
     dimension.  As a special exception, the built-in `min' and `max'
     functions can be used directly, and `accumdim' accounts for the
     middle empty argument that is used in their calling.

     The slices of the returned array that have no subscripts
     associated with them are set to zero.  Defining FILLVAL to some
     other value allows these values to be defined.

     An example of the use of `accumdim' is:

          accumdim ([1, 2, 1, 2, 1], [7,-10,4;-5,-12,8;-12,2,8;-10,9,-3;-5,-3,-13])
          => ans = [-10,-11,-1;-15,-3,5]

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


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

17.5 Utility Functions
======================

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

          ceil ([-2.7, 2.7])
             =>  -2   3

     *See also:* *note floor: doc-floor, *note round: doc-round, *note
     fix: doc-fix.

 -- Function File: [CX, CY, CZ, V] = curl (X, Y, Z, FX, FY, FZ)
 -- Function File: [CZ, V] = curl (X, Y, FX, FY)
 -- Function File: [...] = curl (FX, FY, FZ)
 -- Function File: [...] = curl (FX, FY)
 -- Function File: V = curl (...)
     Calculate curl of vector field given by the arrays FX, FY, and FZ
     or FX, FY respectively.

                            / d         d       d         d       d         d     \
          curl F(x,y,z)  =  | -- Fz  -  -- Fy,  -- Fx  -  -- Fz,  -- Fy  -  -- Fx |
                            \ dy        dz      dz        dx      dx        dy    /

     The coordinates of the vector field can be given by the arguments
     X, Y, Z or X, Y respectively.  V calculates the scalar component
     of the angular velocity vector in direction of the z-axis for
     two-dimensional input.  For three-dimensional input the scalar
     rotation is calculated at each grid point in direction of the
     vector field at that point.

     *See also:* *note divergence: doc-divergence, *note gradient:
     doc-gradient, *note del2: doc-del2, *note cross: doc-cross, *note
     dot: doc-dot.

 -- Function File:  cross (X, Y)
 -- Function File:  cross (X, Y, DIM)
     Compute the vector cross product of 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 forces
     the cross product to be calculated along the specified dimension.

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

 -- Function File: D = del2 (M)
 -- Function File: D = del2 (M, H)
 -- Function File: D = del2 (M, DX, DY, ...)
     Calculate the discrete Laplace operator.  For a 2-dimensional
     matrix M this is defined as

                1    / d^2            d^2         \
          D  = --- * | ---  M(x,y) +  ---  M(x,y) |
                4    \ dx^2           dy^2        /

     For N-dimensional arrays the sum in parentheses is expanded to
     include second derivatives over the additional higher dimensions.

     The spacing between evaluation points may be defined by H, which
     is a scalar defining the equidistant spacing in all dimensions.
     Alternatively, the spacing in each dimension may be defined
     separately by DX, DY, etc.  A scalar spacing argument defines
     equidistant spacing, whereas a vector argument can be used to
     specify variable spacing.  The length of the spacing vectors must
     match the respective dimension of M.  The default spacing value is
     1.

     At least 3 data points are needed for each dimension.  Boundary
     points are calculated from the linear extrapolation of interior
     points.

     *See also:* *note gradient: doc-gradient, *note diff: doc-diff.

 -- Function File: DIV = divergence (X, Y, Z, FX, FY, FZ)
 -- Function File: DIV = divergence (FX, FY, FZ)
 -- Function File: DIV = divergence (X, Y, FX, FY)
 -- Function File: DIV = divergence (FX, FY)
     Calculate divergence of a vector field given by the arrays FX, FY,
     and FZ or FX, FY respectively.

                            d               d               d
          div F(x,y,z)  =   -- F(x,y,z)  +  -- F(x,y,z)  +  -- F(x,y,z)
                            dx              dy              dz

     The coordinates of the vector field can be given by the arguments
     X, Y, Z or X, Y respectively.

     *See also:* *note curl: doc-curl, *note gradient: doc-gradient,
     *note del2: doc-del2, *note cross: doc-cross, *note dot: doc-dot.

 -- Function File: P = factor (Q)
 -- Function File: [P, N] = factor (Q)
     Return prime factorization of Q.  That is, `prod (P) == Q' and
     every element of P is a prime number.  If `Q == 1', return 1.

     With two output arguments, return the unique primes P and their
     multiplicities.  That is, `prod (P .^ N) == Q'.

     *See also:* *note gcd: doc-gcd, *note lcm: doc-lcm.

 -- Function File:  factorial (N)
     Return the factorial of N where N is a positive integer.  If N is
     a scalar, this is equivalent to `prod (1:N)'.  For vector or
     matrix arguments, return the factorial of each element in the
     array.  For non-integers see the generalized factorial function
     `gamma'.

     *See also:* *note prod: doc-prod, *note gamma: doc-gamma.

 -- Mapping Function:  fix (X)
     Truncate fractional portion of X and return the integer portion.
     This is equivalent to rounding towards zero.  If X is complex,
     return `fix (real (X)) + fix (imag (X)) * I'.

          fix ([-2.7, 2.7])
             => -2   2

     *See also:* *note ceil: doc-ceil, *note floor: doc-floor, *note
     round: doc-round.

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

          floor ([-2.7, 2.7])
               => -3   2

     *See also:* *note ceil: doc-ceil, *note round: doc-round, *note
     fix: doc-fix.

 -- Loadable Function: G = gcd (A1, A2, ...)
 -- Loadable Function: [G, V1, ...] = gcd (A1, A2, ...)
     Compute the greatest common divisor of A1, A2, ....  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 each element individually.  All elements must be ordinary or
     Gaussian (complex) integers.  Note that for Gaussian integers, the
     gcd is not unique up to units (multiplication by 1, -1, I or -I),
     so an arbitrary greatest common divisor amongst four possible is
     returned.  For example,

     and

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

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

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

     *See also:* *note lcm: doc-lcm, *note factor: doc-factor.

 -- Function File: DX = gradient (M)
 -- Function File: [DX, DY, DZ, ...] = gradient (M)
 -- Function File: [...] = gradient (M, S)
 -- Function File: [...] = gradient (M, X, Y, Z, ...)
 -- Function File: [...] = gradient (F, X0)
 -- Function File: [...] = gradient (F, X0, S)
 -- Function File: [...] = gradient (F, X0, X, Y, ...)
     Calculate the gradient of sampled data or a function.  If M is a
     vector, calculate the one-dimensional gradient of M.  If M is a
     matrix the gradient is calculated for each dimension.

     `[DX, DY] = gradient (M)' calculates the one dimensional gradient
     for X and Y direction if M is a matrix.  Additional return
     arguments can be use for multi-dimensional matrices.

     A constant spacing between two points can be provided by the S
     parameter.  If S is a scalar, it is assumed to be the spacing for
     all dimensions.  Otherwise, separate values of the spacing can be
     supplied by the X, ... arguments.  Scalar values specify an
     equidistant spacing.  Vector values for the X, ... arguments
     specify the coordinate for that dimension.  The length must match
     their respective dimension of M.

     At boundary points a linear extrapolation is applied.  Interior
     points are calculated with the first approximation of the
     numerical gradient

          y'(i) = 1/(x(i+1)-x(i-1)) * (y(i-1)-y(i+1)).

     If the first argument F is a function handle, the gradient of the
     function at the points in X0 is approximated using central
     difference.  For example, `gradient (@cos, 0)' approximates the
     gradient of the cosine function in the point x0 = 0.  As with
     sampled data, the spacing values between the points from which the
     gradient is estimated can be set via the S or DX, DY, ...
     arguments.  By default a spacing of 1 is used.

     *See also:* *note diff: doc-diff, *note del2: doc-del2.

 -- Built-in Function:  hypot (X, Y)
 -- Built-in Function:  hypot (X, Y, Z, ...)
     Compute the element-by-element square root of the sum of the
     squares of X and Y.  This is equivalent to `sqrt (X.^2 + Y.^2)',
     but calculated in a manner that avoids overflows for large values
     of X or Y.  `hypot' can also be called with more than 2 arguments;
     in this case, the arguments are accumulated from left to right:

            hypot (hypot (X, Y), Z)
            hypot (hypot (hypot (X, Y), Z), W), etc.

 -- Mapping Function:  lcm (X, Y)
 -- Mapping Function:  lcm (X, Y, ...)
     Compute the least common multiple of X and Y, or of the list of
     all arguments.  All elements must be the same size or scalar.

     *See also:* *note factor: doc-factor, *note gcd: doc-gcd.

 -- Function File:  list_primes ()
 -- Function File:  list_primes (N)
     List the first N primes.  If N is unspecified, the first 25 primes
     are listed.

     The algorithm used is from page 218 of the TeXbook.

     *See also:* *note primes: doc-primes, *note isprime: doc-isprime.

 -- Loadable Function:  max (X)
 -- Loadable Function:  max (X, Y)
 -- Loadable Function:  max (X, Y, DIM)
 -- Loadable 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 the matrix 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

     *See also:* *note min: doc-min, *note cummax: doc-cummax, *note
     cummin: doc-cummin.

 -- Loadable Function:  min (X)
 -- Loadable Function:  min (X, Y)
 -- Loadable Function:  min (X, Y, DIM)
 -- Loadable 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, 0])
              =>  x = 0
                  ix = 3

     *See also:* *note max: doc-max, *note cummin: doc-cummin, *note
     cummax: doc-cummax.

 -- Loadable Function:  cummax (X)
 -- Loadable Function:  cummax (X, DIM)
 -- Loadable Function: [W, IW] = cummax (X)
     Return the cumulative maximum values along dimension DIM.  If DIM
     is unspecified it defaults to column-wise operation.  For example:

          cummax ([1 3 2 6 4 5])
              =>  1  3  3  6  6  6

     The call

          [w, iw] = cummax (x, dim)

     with `x' a vector, is equivalent to the following code:

          w = iw = zeros (size (x));
          for i = 1:length (x)
            [w(i), iw(i)] = max (x(1:i));
          endfor

     but computed in a much faster manner.

     *See also:* *note cummin: doc-cummin, *note max: doc-max, *note
     min: doc-min.

 -- Loadable Function:  cummin (X)
 -- Loadable Function:  cummin (X, DIM)
 -- Loadable Function: [W, IW] = cummin (X)
     Return the cumulative minimum values along dimension DIM.  If DIM
     is unspecified it defaults to column-wise operation.  For example:

          cummin ([5 4 6 2 3 1])
              =>  5  4  4  2  2  1

     The call

            [w, iw] = cummin (x)

     with `x' a vector, is equivalent to the following code:

          w = iw = zeros (size (x));
          for i = 1:length (x)
            [w(i), iw(i)] = max (x(1:i));
          endfor

     but computed in a much faster manner.

     *See also:* *note cummax: doc-cummax, *note min: doc-min, *note
     max: doc-max.

 -- Mapping Function:  mod (X, Y)
     Compute the modulo of X and Y.  Conceptually this is given by

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

     and is written such that the correct modulus is returned for
     integer types.  This function handles negative values correctly.
     That is, `mod (-1, 3)' is 2, not -1, as `rem (-1, 3)' returns.
     `mod (X, 0)' returns X.

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

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

 -- Function File:  primes (N)
     Return all primes up to N.

     The algorithm used is the Sieve of Eratosthenes.

     Note that if you need a specific number of primes you can use the
     fact that the distance from one prime to the next is, on average,
     proportional to the logarithm of the prime.  Integrating, one finds
     that there are about k primes less than k*log(5*k).

     *See also:* *note list_primes: doc-list_primes, *note isprime:
     doc-isprime.

 -- Mapping Function:  rem (X, Y)
 -- Mapping Function:  fmod (X, Y)
     Return the remainder of the division `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.

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

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

          round ([-2.7, 2.7])
               => -3   3

     *See also:* *note ceil: doc-ceil, *note floor: doc-floor, *note
     fix: doc-fix.

 -- Mapping Function:  roundb (X)
     Return the integer nearest to X.  If there are two nearest
     integers, return the even one (banker's rounding).  If X is
     complex, return `roundb (real (X)) + roundb (imag (X)) * I'.

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

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


File: octave.info,  Node: Special Functions,  Next: Rational Approximations,  Prev: Utility Functions,  Up: Arithmetic

17.6 Special Functions
======================

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

 -- 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.  If the argument OPT is
          supplied, the result is multiplied by `exp(-abs(imag(X)))'.

    `bessely'
          Bessel functions of the second kind.  If the argument OPT is
          supplied, the result is multiplied by `exp(-abs(imag(X)))'.

    `besseli'
          Modified Bessel functions of the first kind.  If the argument
          OPT is supplied, the result is multiplied by
          `exp(-abs(real(X)))'.

    `besselk'
          Modified Bessel functions of the second kind.  If the
          argument OPT is supplied, the result is multiplied by
          `exp(X)'.

    `besselh'
          Compute Hankel functions of the first (K = 1) or second (K =
          2) kind.  If the argument OPT is supplied, the result is
          multiplied by `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'.

 -- Mapping Function:  beta (A, B)
     For real inputs, 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
                                               /
          betainc (x, a, b) = 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:  betaln (A, B)
     Return the natural logarithm of the Beta function,

          betaln (a, b) = gammaln (a) + gammaln (b) - gammaln (a + b)

     *See also:* *note beta: doc-beta, *note betainc: doc-betainc,
     *note gammaln: doc-gammaln.

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

     In most cases, the `nchoosek' function is faster for small scalar
     integer arguments.  It also warns about loss of precision for big
     arguments.

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

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

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

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

     *See also:* *note erfc: doc-erfc, *note erfcx: doc-erfcx, *note
     erfinv: doc-erfinv.

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

     *See also:* *note erfcx: doc-erfcx, *note erf: doc-erf, *note
     erfinv: doc-erfinv.

 -- Mapping Function:  erfcx (Z)
     Compute the scaled complementary error function, `z^2*(1 - erf
     (Z))'.

     *See also:* *note erfc: doc-erfc, *note erf: doc-erf, *note
     erfinv: doc-erfinv.

 -- Mapping Function:  erfinv (X)
     Compute the inverse error function, i.e., Y such that

            erf(Y) == X

     *See also:* *note erf: doc-erf, *note erfc: doc-erfc, *note erfcx:
     doc-erfcx.

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

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

     *See also:* *note gammainc: doc-gammainc, *note lgamma: doc-lgamma.

 -- Mapping Function:  gammainc (X, A)
 -- Mapping Function:  gammainc (X, A, "lower")
 -- Mapping Function:  gammainc (X, A, "upper")
     Compute the normalized incomplete gamma function,

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

     with the limiting value of 1 as X approaches infinity.  The
     standard notation is P(a,x), e.g., Abramowitz and Stegun (6.5.1).

     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.

     By default the incomplete gamma function integrated from 0 to X is
     computed.  If "upper" is given then the complementary function
     integrated from X to infinity is calculated.  It should be noted
     that

          gammainc (X, A) == 1 - gammainc (X, A, "upper")

     *See also:* *note gamma: doc-gamma, *note lgamma: doc-lgamma.

 -- Function File: L = legendre (N, X)
 -- Function File: L = legendre (N, X, NORMALIZATION)
     Compute the Legendre function of degree N and order M = 0 ... N.
     The optional argument, NORMALIZATION, may be one of `"unnorm"',
     `"sch"', or `"norm"'.  The default is `"unnorm"'.  The value of N
     must be a non-negative scalar integer.

     If the optional argument NORMALIZATION is missing or is
     `"unnorm"', compute the Legendre function of degree N and order M
     and return all values for M = 0 ... N.  The return value has one
     dimension more than X.

     The Legendre Function of degree N and order M:

           m        m       2  m/2   d^m
          P(x) = (-1) * (1-x  )    * ----  P (x)
           n                         dx^m   n

     with Legendre polynomial of degree N:

                    1     d^n   2    n
          P (x) = ------ [----(x - 1)  ]
           n      2^n n!  dx^n

     `legendre (3, [-1.0, -0.9, -0.8])' returns the matrix:

           x  |   -1.0   |   -0.9   |  -0.8
          ------------------------------------
          m=0 | -1.00000 | -0.47250 | -0.08000
          m=1 |  0.00000 | -1.99420 | -1.98000
          m=2 |  0.00000 | -2.56500 | -4.32000
          m=3 |  0.00000 | -1.24229 | -3.24000

     If the optional argument `normalization' is `"sch"', compute the
     Schmidt semi-normalized associated Legendre function.  The Schmidt
     semi-normalized associated Legendre function is related to the
     unnormalized Legendre functions by the following:

     For Legendre functions of degree n and order 0:

            0       0
          SP (x) = P (x)
            n       n

     For Legendre functions of degree n and order m:

            m       m          m    2(n-m)! 0.5
          SP (x) = P (x) * (-1)  * [-------]
            n       n               (n+m)!

     If the optional argument NORMALIZATION is `"norm"', compute the
     fully normalized associated Legendre function.  The fully
     normalized associated Legendre function is related to the
     unnormalized Legendre functions by the following:

     For Legendre functions of degree N and order M

            m       m          m    (n+0.5)(n-m)! 0.5
          NP (x) = P (x) * (-1)  * [-------------]
            n       n                   (n+m)!


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

     *See also:* *note gamma: doc-gamma, *note gammainc: doc-gammainc.


File: octave.info,  Node: Rational Approximations,  Next: Coordinate Transformations,  Prev: Special Functions,  Up: Arithmetic

17.7 Rational Approximations
============================

 -- Function File: S = rat (X, TOL)
 -- Function File: [N, D] = rat (X, TOL)
     Find a rational approximation to X within the tolerance defined by
     TOL using a continued fraction expansion.  For example:

          rat(pi) = 3 + 1/(7 + 1/16) = 355/113
          rat(e) = 3 + 1/(-4 + 1/(2 + 1/(5 + 1/(-2 + 1/(-7)))))
                 = 1457/536

     Called with two arguments returns the numerator and denominator
     separately as two matrices.

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

 -- Built-in Function:  rats (X, LEN)
     Convert X into a rational approximation represented as a string.
     You can convert the string back into a matrix as follows:

             r = rats(hilb(4));
             x = str2num(r)

     The optional second argument defines the maximum length of the
     string representing the elements of X.  By default LEN is 9.

     *See also:* *note format: doc-format, *note rat: doc-rat.


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

17.8 Coordinate Transformations
===============================

 -- Function File: [THETA, R] = cart2pol (X, Y)
 -- Function File: [THETA, R, Z] = cart2pol (X, Y, Z)
 -- Function File: [THETA, R] = cart2pol (C)
 -- Function File: [THETA, R, Z] = cart2pol (C)
 -- Function File: P = cart2pol (...)
     Transform Cartesian to polar or cylindrical coordinates.

     THETA describes the angle relative to the positive x-axis.  R is
     the distance to the z-axis (0, 0, z).  X, Y (and Z) must be the
     same shape, or scalar.  If called with a single matrix argument
     then each row of C represents the Cartesian coordinate (X, Y (,
     Z)).

     If only a single return argument is requested then return a matrix
     P where each row represents one polar/(cylindrical) coordinate
     (THETA, PHI (, Z)).

     *See also:* *note pol2cart: doc-pol2cart, *note cart2sph:
     doc-cart2sph, *note sph2cart: doc-sph2cart.

 -- Function File: [X, Y] = pol2cart (THETA, R)
 -- Function File: [X, Y, Z] = pol2cart (THETA, R, Z)
 -- Function File: [X, Y] = pol2cart (P)
 -- Function File: [X, Y, Z] = pol2cart (P)
 -- Function File: C = pol2cart (...)
     Transform polar or cylindrical to Cartesian coordinates.

     THETA, R, (and Z) must be the same shape, or scalar.  THETA
     describes the angle relative to the positive x-axis.  R is the
     distance to the z-axis (0, 0, z).  If called with a single matrix
     argument then each row of P represents the polar/(cylindrical)
     coordinate (X, Y (, Z)).

     If only a single return argument is requested then return a matrix
     C where each row represents one Cartesian coordinate (X, Y (, Z)).

     *See also:* *note cart2pol: doc-cart2pol, *note sph2cart:
     doc-sph2cart, *note cart2sph: doc-cart2sph.

 -- Function File: [THETA, PHI, R] = cart2sph (X, Y, Z)
 -- Function File: [THETA, PHI, R] = cart2sph (C)
 -- Function File: S = cart2sph (...)
     Transform Cartesian to spherical coordinates.

     THETA describes the angle relative to the positive x-axis.  PHI is
     the angle relative to the xy-plane.  R is the distance to the
     origin (0, 0, 0).  X, Y, and Z must be the same shape, or scalar.
     If called with a single matrix argument then each row of C
     represents the Cartesian coordinate (X, Y, Z).

     If only a single return argument is requested then return a matrix
     S where each row represents one spherical coordinate (THETA, PHI,
     R).

     *See also:* *note sph2cart: doc-sph2cart, *note cart2pol:
     doc-cart2pol, *note pol2cart: doc-pol2cart.

 -- Function File: [X, Y, Z] = sph2cart (THETA, PHI, R)
 -- Function File: [X, Y, Z] = sph2cart (S)
 -- Function File: C = sph2cart (...)
     Transform spherical to Cartesian coordinates.

     THETA describes the angle relative to the positive x-axis.  PHI is
     the angle relative to the xy-plane.  R is the distance to the
     origin (0, 0, 0).  THETA, PHI, and R must be the same shape, or
     scalar.  If called with a single matrix argument then each row of S
     represents the spherical coordinate (THETA, PHI, R).

     If only a single return argument is requested then return a matrix
     C where each row represents one Cartesian coordinate (X, Y, Z).

     *See also:* *note cart2sph: doc-cart2sph, *note pol2cart:
     doc-pol2cart, *note cart2pol: doc-cart2pol.


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

17.9 Mathematical Constants
===========================

 -- Built-in Function:  e
 -- Built-in Function:  e (N)
 -- Built-in Function:  e (N, M)
 -- Built-in Function:  e (N, M, K, ...)
 -- Built-in Function:  e (..., CLASS)
     Return a scalar, matrix, or N-dimensional array whose elements are
     all equal to the base of natural logarithms.  The constant `e'
     satisfies the equation `log' (e) = 1.

     When called with no arguments, return a scalar with the value e.
     When called with a single argument, return a square matrix with
     the dimension specified.  When called with more than one scalar
     argument the first two arguments are taken as the number of rows
     and columns and any further arguments specify additional matrix
     dimensions.  The optional argument CLASS specifies the return type
     and may be either "double" or "single".

 -- Built-in Function:  pi
 -- Built-in Function:  pi (N)
 -- Built-in Function:  pi (N, M)
 -- Built-in Function:  pi (N, M, K, ...)
 -- Built-in Function:  pi (..., CLASS)
     Return a scalar, matrix, or N-dimensional array whose elements are
     all equal to the ratio of the circumference of a circle to its
     diameter.  Internally, `pi' is computed as `4.0 * atan (1.0)'.

     When called with no arguments, return a scalar with the value of
     pi.  When called with a single argument, return a square matrix
     with the dimension specified.  When called with more than one
     scalar argument the first two arguments are taken as the number of
     rows and columns and any further arguments specify additional
     matrix dimensions.  The optional argument CLASS specifies the
     return type and may be either "double" or "single".

 -- Built-in Function:  I
 -- Built-in Function:  I (N)
 -- Built-in Function:  I (N, M)
 -- Built-in Function:  I (N, M, K, ...)
 -- Built-in Function:  I (..., CLASS)
     Return a scalar, matrix, or N-dimensional array whose elements are
     all equal to the pure imaginary unit, defined as `sqrt (-1)'.   I,
     and its equivalents i, J, and j, are functions so any of the names
     may be reused for other purposes (such as i for a counter
     variable).

     When called with no arguments, return a scalar with the value i.
     When called with a single argument, return a square matrix with
     the dimension specified.  When called with more than one scalar
     argument the first two arguments are taken as the number of rows
     and columns and any further arguments specify additional matrix
     dimensions.  The optional argument CLASS specifies the return type
     and may be either "double" or "single".

 -- Built-in Function:  Inf
 -- Built-in Function:  Inf (N)
 -- Built-in Function:  Inf (N, M)
 -- Built-in Function:  Inf (N, M, K, ...)
 -- Built-in Function:  Inf (..., CLASS)
     Return a scalar, matrix or N-dimensional array whose elements are
     all equal to the IEEE representation for positive infinity.

     Infinity is produced when results are too large to be represented
     using the the IEEE floating point format for numbers.  Two common
     examples which produce infinity are division by zero and overflow.

          [1/0 e^800]
          =>
          Inf   Inf

     When called with no arguments, return a scalar with the value
     `Inf'.  When called with a single argument, return a square matrix
     with the dimension specified.  When called with more than one
     scalar argument the first two arguments are taken as the number of
     rows and columns and any further arguments specify additional
     matrix dimensions.  The optional argument CLASS specifies the
     return type and may be either "double" or "single".

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

 -- Built-in Function:  NaN
 -- Built-in Function:  NaN (N)
 -- Built-in Function:  NaN (N, M)
 -- Built-in Function:  NaN (N, M, K, ...)
 -- Built-in Function:  NaN (..., CLASS)
     Return a scalar, matrix, or N-dimensional array whose elements are
     all equal to the IEEE symbol NaN (Not a Number).  NaN is the
     result of operations which do not produce a well defined numerical
     result.  Common operations which produce a NaN are arithmetic with
     infinity (Inf - Inf), zero divided by zero (0/0), and any
     operation involving another NaN value (5 + NaN).

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

     When called with no arguments, return a scalar with the value
     `NaN'.  When called with a single argument, return a square matrix
     with the dimension specified.  When called with more than one
     scalar argument the first two arguments are taken as the number of
     rows and columns and any further arguments specify additional
     matrix dimensions.  The optional argument CLASS specifies the
     return type and may be either "double" or "single".

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

 -- Built-in Function:  eps
 -- Built-in Function:  eps (X)
 -- Built-in Function:  eps (N, M)
 -- Built-in Function:  eps (N, M, K, ...)
 -- Built-in Function:  eps (..., CLASS)
     Return a scalar, matrix or N-dimensional array whose elements are
     all eps, the machine precision.  More precisely, `eps' is the
     relative spacing between any two adjacent numbers in the machine's
     floating point system.  This number is obviously system dependent.
     On machines that support IEEE floating point arithmetic, `eps' is
     approximately 2.2204e-16 for double precision and 1.1921e-07 for
     single precision.

     When called with no arguments, return a scalar with the value
     `eps(1.0)'.  Given a single argument X, return the distance
     between X and the next largest value.  When called with more than
     one argument the first two arguments are taken as the number of
     rows and columns and any further arguments specify additional
     matrix dimensions.  The optional argument CLASS specifies the
     return type and may be either "double" or "single".

 -- Built-in Function:  realmax
 -- Built-in Function:  realmax (N)
 -- Built-in Function:  realmax (N, M)
 -- Built-in Function:  realmax (N, M, K, ...)
 -- Built-in Function:  realmax (..., CLASS)
     Return a scalar, matrix or N-dimensional array whose elements are
     all equal to the largest floating point number that is
     representable.  The actual value is system dependent.  On machines
     that support IEEE floating point arithmetic, `realmax' is
     approximately 1.7977e+308 for double precision and 3.4028e+38 for
     single precision.

     When called with no arguments, return a scalar with the value
     `realmax("double")'.  When called with a single argument, return a
     square matrix with the dimension specified.  When called with more
     than one scalar argument the first two arguments are taken as the
     number of rows and columns and any further arguments specify
     additional matrix dimensions.  The optional argument CLASS
     specifies the return type and may be either "double" or "single".

     *See also:* *note realmin: doc-realmin, *note intmax: doc-intmax,
     *note bitmax: doc-bitmax.

 -- Built-in Function:  realmin
 -- Built-in Function:  realmin (N)
 -- Built-in Function:  realmin (N, M)
 -- Built-in Function:  realmin (N, M, K, ...)
 -- Built-in Function:  realmin (..., CLASS)
     Return a scalar, matrix or N-dimensional array whose elements are
     all equal to the smallest normalized floating point number that is
     representable.  The actual value is system dependent.  On machines
     that support IEEE floating point arithmetic, `realmin' is
     approximately 2.2251e-308 for double precision and 1.1755e-38 for
     single precision.

     When called with no arguments, return a scalar with the value
     `realmin("double")'.  When called with a single argument, return a
     square matrix with the dimension specified.  When called with more
     than one scalar argument the first two arguments are taken as the
     number of rows and columns and any further arguments specify
     additional matrix dimensions.  The optional argument CLASS
     specifies the return type and may be either "double" or "single".

     *See also:* *note realmax: doc-realmax, *note intmin: doc-intmin.


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

18 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 the `LAPACK Users' Guide', SIAM, 1992.

* Menu:

* Techniques Used for Linear Algebra::
* Basic Matrix Functions::
* Matrix Factorizations::
* Functions of a Matrix::
* Specialized Solvers::


File: octave.info,  Node: Techniques Used for Linear Algebra,  Next: Basic Matrix Functions,  Up: Linear Algebra

18.1 Techniques Used for Linear Algebra
=======================================

Octave includes a polymorphic solver, that selects an appropriate
matrix factorization depending on the properties of the matrix itself.
Generally, the cost of determining the matrix type is small relative to
the cost of factorizing the matrix itself, but in any case the matrix
type is cached once it is calculated, so that it is not re-determined
each time it is used in a linear equation.

   The selection tree for how the linear equation is solve or a matrix
inverse is form is given by

  1. If the matrix is upper or lower triangular sparse a forward or
     backward substitution using the LAPACK xTRTRS function, and goto 4.

  2. If the matrix is square, Hermitian with a real positive diagonal,
     attempt Cholesky factorization using the LAPACK xPOTRF function.

  3. If the Cholesky factorization failed or the matrix is not
     Hermitian with a real positive diagonal, and the matrix is square,
     factorize using the LAPACK xGETRF function.

  4. If the matrix is not square, or any of the previous solvers flags
     a singular or near singular matrix, find a least squares solution
     using the LAPACK xGELSD function.

   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 that identifying the type of the
matrix incorrectly will lead to unpredictable results, and so
`matrix_type' should be used with care.

   It should be noted that the test for whether a matrix is a candidate
for Cholesky factorization, performed above and by the `matrix_type'
function, does not give a certainty that the matrix is Hermitian.
However, the attempt to factorize the matrix will quickly flag a
non-Hermitian matrix.


File: octave.info,  Node: Basic Matrix Functions,  Next: Matrix Factorizations,  Prev: Techniques Used for Linear Algebra,  Up: Linear Algebra

18.2 Basic Matrix Functions
===========================

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

     If two output values are requested, `balance' returns the diagonal
     D and the permutation P separately as vectors.  In this case, `DD
     = eye(n)(:,P) * diag (D)', where n n is the matrix size.

     If four output values are requested, compute `AA = CC*A*DD' and
     `BB = CC*B*DD', in which 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 may be one of:

    "noperm", "S"
          Scale only; do not permute.

    "noscal", "P"
          Permute only; do not scale.

     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)
 -- Function File:  cond (A, P)
     Compute the P-norm condition number of a matrix.  `cond (A)' is
     defined as `norm (A, P) * norm (inv (A), P)'.

     By default `P = 2' is used which implies a (relatively slow)
     singular value decomposition.  Other possible selections are `P =
     1, Inf, "fro"' which are generally faster.  See `norm' for a full
     discussion of possible P values.

     *See also:* *note condest: doc-condest, *note rcond: doc-rcond,
     *note norm: doc-norm, *note svd: doc-svd.

 -- Loadable Function:  det (A)
 -- Loadable Function: [D, RCOND] = det (A)
     Compute the determinant of A.

     Return an estimate of the reciprocal condition number if requested.

     Routines from LAPACK are used for full matrices and code from
     UMFPACK is used for sparse matrices.

     The determinant should not be used to check a matrix for
     singularity.  For that, use any of the condition number functions:
     `cond', `condest', `rcond'.

     *See also:* *note cond: doc-cond, *note condest: doc-condest,
     *note rcond: doc-rcond.

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

     This is equivalent to `sum (conj (X) .* Y, DIM)', but avoids
     forming a temporary array and is faster.  When X and Y are column
     vectors, the result is equivalent to `X' * Y'.

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

 -- Loadable Function: LAMBDA = eig (A)
 -- Loadable Function: LAMBDA = eig (A, B)
 -- Loadable Function: [V, LAMBDA] = eig (A)
 -- Loadable Function: [V, LAMBDA] = eig (A, B)
     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.

     The eigenvalues returned by `eig' are not ordered.

     *See also:* *note eigs: doc-eigs, *note svd: doc-svd.

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

 -- Function File: [G, Y] = planerot (X)
     Given a two-element column vector, returns the 2 by 2 orthogonal
     matrix G such that `Y = G * X' and `Y(2) = 0'.

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

 -- Loadable Function: [X = inv (A)
 -- Loadable Function: [X, RCOND] = inv (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.

     In general it is best to avoid calculating the inverse of a matrix
     directly.  For example, it is both faster and more accurate to
     solve systems of equations (A*x = b) with `Y = A \ b', rather than
     `Y = inv (A) * b'.

     If called with a sparse matrix, then in general X will be a full
     matrix requiring significantly more storage.  Avoid forming the
     inverse of a sparse matrix if possible.

     *See also:* *note ldivide: doc-ldivide, *note rdivide: doc-rdivide.

 -- Loadable Function: TYPE = matrix_type (A)
 -- Loadable Function: TYPE = matrix_type (A, 'nocompute')
 -- 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 more rapid 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.

     If the option 'nocompute' is given, the function will not attempt
     to guess the type if it is still unknown.  This is useful for
     debugging purposes.

     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'
          Probable 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 probably a 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; it is
     entirely *the responsibility of the user* to correctly identify
     the matrix type.

     Also, the test for positive definiteness is a low-cost test for a
     Hermitian matrix with a real positive diagonal.  This does not
     guarantee that the matrix is positive definite, but only that it
     is a probable candidate.  When such a matrix is factorized, a
     Cholesky factorization is first attempted, and if that fails the
     matrix is then treated with an LU factorization.  Once the matrix
     has been factorized, `matrix_type' will return the correct
     classification of the matrix.

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

     If A is a matrix (or sparse matrix):

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

    P = `2'
          Largest singular value of A.

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

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

    other P, `P > 1'
          maximum `norm (A*x, p)' such that `norm (x, p) == 1'

     If A is a vector or a scalar:

    P = `Inf' or `"inf"'
          `max (abs (A))'.

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

    P = `"fro"'
          Frobenius norm of A, `sqrt (sumsq (abs (a)))'.

    P = 0
          Hamming norm - the number of nonzero elements.

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

    other P `P < 1'
          the p-pseudonorm defined as above.

     If OPT is the value `"rows"', treat each row as a vector and
     compute its norm.  The result is returned as a column vector.
     Similarly, if OPT is `"columns"' or `"cols"' then compute the
     norms of each column and return a row vector.

     *See also:* *note cond: doc-cond, *note svd: doc-svd.

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

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

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

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

 -- Loadable Function:  pinv (X)
 -- 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.

 -- Loadable Function: C = rcond (A)
     Compute the 1-norm estimate of the reciprocal condition number as
     returned by LAPACK.  If the matrix is well-conditioned then C will
     be near 1 and if the matrix is poorly conditioned it will be close
     to zero.

     The matrix A must not be sparse.  If the matrix is sparse then
     `condest (A)' or `rcond (full (A))' should be used instead.

     *See also:* *note cond: doc-cond, *note condest: doc-condest.

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

 -- Function File: [R, K] = rref (A, TOL)
     Returns the reduced row echelon form of A.  TOL defaults to `eps *
     max (size (A)) * norm (A, inf)'.

     Called with two return arguments, K returns the vector of "bound
     variables", which are those columns on which elimination has been
     performed.



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

18.3 Matrix Factorizations
==========================

 -- Loadable Function: R = chol (A)
 -- Loadable Function: [R, P] = chol (A)
 -- Loadable Function: [R, P, Q] = chol (S)
 -- Loadable Function: [R, P, Q] = chol (S, 'vector')
 -- Loadable Function: [L, ...] = chol (..., 'lower')
     Compute the Cholesky factor, R, of the symmetric positive definite
     matrix A, where

          R' * R = A.

     Called with one output argument `chol' fails if A or S is not
     positive definite.  With two or more output arguments P flags
     whether the matrix was positive definite and `chol' does not fail.
     A zero value indicated that the matrix was positive definite and
     the R gives the factorization, and P will have a positive value
     otherwise.

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

          R' * R = Q' * A * Q.

     The sparsity preserving permutation is generally returned as a
     matrix.  However, given the flag 'vector', Q will be returned as a
     vector such that

          R' * R = A(Q, Q).

     Called with either a sparse or full matrix and using the 'lower'
     flag, `chol' returns the lower triangular factorization such that

          L * L' = A.

     In general the lower triangular factorization is significantly
     faster for sparse matrices.

     *See also:* *note cholinv: doc-cholinv, *note chol2inv:
     doc-chol2inv.

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

     *See also:* *note chol: doc-chol, *note chol2inv: doc-chol2inv,
     *note inv: doc-inv.

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

     *See also:* *note chol: doc-chol, *note cholinv: doc-cholinv,
     *note inv: doc-inv.

 -- Loadable Function: [R1, INFO] = cholupdate (R, U, OP)
     Update or downdate a Cholesky factorization.  Given an upper
     triangular matrix R and a column vector U, attempt to determine
     another upper triangular matrix R1 such that
        * R1'*R1 = R'*R + U*U' if OP is "+"

        * R1'*R1 = R'*R - U*U' if OP is "-"

     If OP is "-", INFO is set to
        * 0 if the downdate was successful,

        * 1 if R'*R - U*U' is not positive definite,

        * 2 if R is singular.

     If INFO is not present, an error message is printed in cases 1 and
     2.

     *See also:* *note chol: doc-chol, *note qrupdate: doc-qrupdate.

 -- Loadable Function: R1 = cholinsert (R, J, U)
 -- Loadable Function: [R1, INFO] = cholinsert (R, J, U)
     Given a Cholesky factorization of a real symmetric or complex
     Hermitian positive definite matrix A = R'*R, R upper triangular,
     return the Cholesky factorization of A1, where A1(p,p) = A,
     A1(:,j) = A1(j,:)' = u and p = [1:j-1,j+1:n+1].  u(j) should be
     positive.  On return, INFO is set to
        * 0 if the insertion was successful,

        * 1 if A1 is not positive definite,

        * 2 if R is singular.

     If INFO is not present, an error message is printed in cases 1 and
     2.

     *See also:* *note chol: doc-chol, *note cholupdate:
     doc-cholupdate, *note choldelete: doc-choldelete.

 -- Loadable Function: R1 = choldelete (R, J)
     Given a Cholesky factorization of a real symmetric or complex
     Hermitian positive definite matrix A = R'*R, R upper triangular,
     return the Cholesky factorization of A(p,p), where
     p = [1:j-1,j+1:n+1].

     *See also:* *note chol: doc-chol, *note cholupdate:
     doc-cholupdate, *note cholinsert: doc-cholinsert.

 -- Loadable Function: R1 = cholshift (R, I, J)
     Given a Cholesky factorization of a real symmetric or complex
     Hermitian positive definite matrix A = R'*R, R upper triangular,
     return the Cholesky factorization of A(p,p), where p is the
     permutation
     `p = [1:i-1, shift(i:j, 1), j+1:n]' if I < J
     or
     `p = [1:j-1, shift(j:i,-1), i+1:n]' if J < I.
     *See also:* *note chol: doc-chol, *note cholinsert:
     doc-cholinsert, *note choldelete: doc-choldelete.

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

     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 (`H(i, j) = 0 forall i >=
     j+1)'.

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

 -- Loadable Function: [L, U] = lu (A)
 -- Loadable Function: [L, U, P] = lu (A)
 -- Loadable Function: [L, U, P, Q] = lu (S)
 -- Loadable Function: [L, U, P, Q, R] = lu (S)
 -- Loadable Function: [...] = lu (S, THRES)
 -- Loadable Function: Y = lu (...)
 -- Loadable Function: [...] = lu (..., 'vector')
     Compute the LU decomposition of A.  If A is full subroutines from
     LAPACK are used and if A is sparse then UMFPACK is used.  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.

     When called with two or three output arguments and a spare input
     matrix, `lu' does not attempt to perform sparsity preserving column
     permutations.  Called with a fourth output argument, the sparsity
     preserving column transformation Q is returned, such that `P * A *
     Q = L * U'.

     Called with a fifth output argument and a sparse input matrix,
     `lu' attempts to use a scaling factor R on the input matrix such
     that `P * (R \ A) * Q = L * U'.  This typically leads to a sparser
     and more stable factorization.

     An additional input argument THRES, that defines the pivoting
     threshold can be given.  THRES can be a scalar, in which case it
     defines the UMFPACK pivoting tolerance for both symmetric and
     unsymmetric cases.  If THRES is a 2-element vector, then the first
     element defines the pivoting tolerance for the unsymmetric UMFPACK
     pivoting strategy and the second for the symmetric strategy.  By
     default, the values defined by `spparms' are used ([0.1, 0.001]).

     Given the string argument 'vector', `lu' returns the values of P
     and Q as vector values, such that for full matrix, `A (P,:) = L *
     U', and `R(P,:) * A (:, Q) = L * U'.

     With two output arguments, returns the permuted forms of the upper
     and lower triangular matrices, such that `A = L * U'.  With one
     output argument Y, then the matrix returned by the LAPACK routines
     is returned.  If the input matrix is sparse then the matrix L is
     embedded into U to give a return value similar to the full case.
     For both full and sparse matrices, `lu' loses the permutation
     information.

 -- Loadable Function: [L, U] = luupdate (L, U, X, Y)
 -- Loadable Function: [L, U, P] = luupdate (L, U, P, X, Y)
     Given an LU factorization of a real or complex matrix A = L*U,
     L lower unit trapezoidal and U upper trapezoidal, return the
     LU factorization of A + X*Y.', where X and Y are column vectors
     (rank-1 update) or matrices with equal number of columns (rank-k
     update).  Optionally, row-pivoted updating can be used by supplying
     a row permutation (pivoting) matrix P; in that case, an updated
     permutation matrix is returned.  Note that if L, U, P is a pivoted
     LU factorization as obtained by `lu':

            [L, U, P] = lu (A);

     then a factorization of `A+X*Y.'' can be obtained either as

            [L1, U1] = lu (L, U, P*X, Y)

     or

            [L1, U1, P1] = lu (L, U, P, X, Y)

     The first form uses the unpivoted algorithm, which is faster, but
     less stable.  The second form uses a slower pivoted algorithm,
     which is more stable.

     The matrix case is done as a sequence of rank-1 updates; thus, for
     large enough k, it will be both faster and more accurate to
     recompute the factorization from scratch.

     *See also:* *note lu: doc-lu, *note qrupdate: doc-qrupdate, *note
     cholupdate: doc-cholupdate.

 -- Loadable Function: [Q, R, P] = qr (A)
 -- Loadable Function: [Q, R, P] = qr (A, '0')
     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 * Q = A' where Q is an
     orthogonal matrix and R is upper triangular.

     If given a second argument of '0', `qr' returns an economy-sized
     QR factorization, omitting zero rows of R and the corresponding
     columns of Q.

     If the matrix A is full, 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)'.

     If the matrix A is sparse, then compute the sparse
     QR factorization of A, using CSPARSE.  As the matrix Q is in
     general a full matrix, this function returns the Q-less
     factorization R of A, such that `R = chol (A' * A)'.

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

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

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

 -- Loadable Function: [Q1, R1] = qrupdate (Q, R, U, V)
     Given a QR factorization of a real or complex matrix A = Q*R,
     Q unitary and R upper trapezoidal, return the QR factorization of
     A + U*V', where U and V are column vectors (rank-1 update) or
     matrices with equal number of columns (rank-k update).  Notice
     that the latter case is done as a sequence of rank-1 updates;
     thus, for k large enough, it will be both faster and more accurate
     to recompute the factorization from scratch.

     The QR factorization supplied may be either full (Q is square) or
     economized (R is square).

     *See also:* *note qr: doc-qr, *note qrinsert: doc-qrinsert, *note
     qrdelete: doc-qrdelete.

 -- Loadable Function: [Q1, R1] = qrinsert (Q, R, J, X, ORIENT)
     Given a QR factorization of a real or complex matrix A = Q*R,
     Q unitary and R upper trapezoidal, return the QR factorization of
     [A(:,1:j-1) x A(:,j:n)], where U is a column vector to be inserted
     into A (if ORIENT is `"col"'), or the QR factorization of
     [A(1:j-1,:);x;A(:,j:n)], where X is a row vector to be inserted
     into A (if ORIENT is `"row"').

     The default value of ORIENT is `"col"'.  If ORIENT is `"col"', U
     may be a matrix and J an index vector resulting in the
     QR factorization of a matrix B such that B(:,J) gives U and
     B(:,J) = [] gives A.  Notice that the latter case is done as a
     sequence of k insertions; thus, for k large enough, it will be
     both faster and more accurate to recompute the factorization from
     scratch.

     If ORIENT is `"col"', the QR factorization supplied may be either
     full (Q is square) or economized (R is square).

     If ORIENT is `"row"', full factorization is needed.

     *See also:* *note qr: doc-qr, *note qrupdate: doc-qrupdate, *note
     qrdelete: doc-qrdelete.

 -- Loadable Function: [Q1, R1] = qrdelete (Q, R, J, ORIENT)
     Given a QR factorization of a real or complex matrix A = Q*R,
     Q unitary and R upper trapezoidal, return the QR factorization of
     [A(:,1:j-1) A(:,j+1:n)], i.e., A with one column deleted (if
     ORIENT is "col"), or the QR factorization of
     [A(1:j-1,:);A(:,j+1:n)], i.e., A with one row deleted (if ORIENT
     is "row").

     The default value of ORIENT is "col".

     If ORIENT is `"col"', J may be an index vector resulting in the
     QR factorization of a matrix B such that A(:,J) = [] gives B.
     Notice that the latter case is done as a sequence of k deletions;
     thus, for k large enough, it will be both faster and more accurate
     to recompute the factorization from scratch.

     If ORIENT is `"col"', the QR factorization supplied may be either
     full (Q is square) or economized (R is square).

     If ORIENT is `"row"', full factorization is needed.

     *See also:* *note qr: doc-qr, *note qrinsert: doc-qrinsert, *note
     qrupdate: doc-qrupdate.

 -- Loadable Function: [Q1, R1] = qrshift (Q, R, I, J)
     Given a QR factorization of a real or complex matrix A = Q*R,
     Q unitary and R upper trapezoidal, return the QR factorization of
     A(:,p), where p is the permutation
     `p = [1:i-1, shift(i:j, 1), j+1:n]' if I < J
     or
     `p = [1:j-1, shift(j:i,-1), i+1:n]' if J < I.
     *See also:* *note qr: doc-qr, *note qrinsert: doc-qrinsert, *note
     qrdelete: doc-qrdelete.

 -- Loadable Function: LAMBDA = qz (A, B)
 -- Loadable Function: LAMBDA = qz (A, B, OPT)
     QZ decomposition of the generalized eigenvalue problem (A x = s B
     x).  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 - s B)


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

              "+"
                    = non-negative real part: leading block has all
                    eigenvalues in the closed right half-plane

     Note: `qz' performs permutation balancing, but not scaling (*note
     doc-balance::).  The order of output arguments was selected for
     compatibility with MATLAB.

     *See also:* *note balance: doc-balance, *note eig: doc-eig, *note
     schur: doc-schur.

 -- 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: S = schur (A, "complex")
 -- 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.

     A complex decomposition may be forced by passing "complex" as OPT.

     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.

 -- Function File: [U, T] = rsf2csf (UR, TR)
     Convert a real, upper quasi-triangular Schur form TR to a complex,
     upper triangular Schur form T.

     Note that the following relations hold:

     `UR * TR * UR' = U * T * U'' and `U' * U' is the identity matrix I.

     Note also that U and T are not unique.

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

 -- Function File: ANGLE = subspace (A, B)
     Determine the largest principal angle between two subspaces
     spanned by the columns of matrices A and B.

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

          A = U*S*V'

     The function `svd' normally returns only the vector of singular
     values.  When called with 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.

     *See also:* *note svd_driver: doc-svd_driver, *note svds:
     doc-svds, *note eig: doc-eig.

 -- Loadable Function: OLD = svd_driver (NEW)
     Set or query the underlying LAPACK driver used by `svd'.
     Currently recognized values are "gesvd" and "gesdd".  The default
     is "gesvd".

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

 -- Function File: [HOUSV, BETA, ZER] = housh (X, J, Z)
     Compute Householder reflection vector HOUSV to reflect X to be the
     j-th column of identity, i.e.,

          (I - beta*housv*housv')x =  norm(x)*e(j) if x(1) < 0,
          (I - beta*housv*housv')x = -norm(x)*e(j) if x(1) >= 0

     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 an orthogonal basis U of block Krylov subspace

          [v a*v a^2*v ... a^(k+1)*v]

     Using Householder reflections to guard against loss of
     orthogonality.

     If V is a vector, then H contains the Hessenberg matrix such that
     `a*u == u*h+rk*ek'', in which `rk = a*u(:,k)-u*h(:,k)', and `ek''
     is the vector `[0, 0, ..., 1]' of length `k'.  Otherwise, H is
     meaningless.

     If V is a vector and K is greater than `length(A)-1', then H
     contains the Hessenberg matrix such that `a*u == u*h'.

     The value of NU is the dimension of the span of the Krylov
     subspace (based on EPS1).

     If B is a vector and K is greater than M-1, then H contains the
     Hessenberg decomposition of A.

     The optional parameter EPS1 is the threshold for zero.  The
     default value is 1e-12.

     If the optional parameter PFLG is nonzero, row pivoting is used to
     improve numerical behavior.  The default value is 0.

     Reference: A. Hodel, P. Misra, `Partial Pivoting in the
     Computation of Krylov Subspaces of Large Sparse Systems',
     Proceedings of the 42nd IEEE Conference on Decision and Control,
     December 2003.


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

18.4 Functions of a Matrix
==========================

 -- Function File:  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: S = logm (A)
 -- Function File: S = logm (A, OPT_ITERS)
 -- Function File: [S, ITERS] = logm (...)
     Compute the matrix logarithm of the square matrix A.  The
     implementation utilizes a Pade' approximant and the identity

          logm(A) = 2^k * logm(A^(1 / 2^k))

     The optional argument OPT_ITERS is the maximum number of square
     roots to compute and defaults to 100.  The optional output ITERS
     is the number of square roots actually computed.


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

     Ref: N.J. Higham.  `A New sqrtm for MATLAB'.  Numerical Analysis
     Report No. 336, Manchester Centre for Computational Mathematics,
     Manchester, England, January 1999.

     *See also:* *note expm: doc-expm, *note logm: doc-logm.

 -- Loadable Function:  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: Specialized Solvers,  Prev: Functions of a Matrix,  Up: Linear Algebra

18.5 Specialized Solvers
========================

 -- Function File:  bicgstab (A, B)
 -- Function File:  bicgstab (A, B, TOL, MAXIT, M1, M2, X0)
     This procedure attempts to solve a system of linear equations A*x
     = b for x.  The A must be square, symmetric and positive definite
     real matrix N*N.  The B must be a one column vector with a length
     of N.  The TOL specifies the tolerance of the method, the default
     value is 1e-6.  The MAXIT specifies the maximum number of
     iterations, the default value is min(20,N).  The M1 specifies a
     preconditioner, can also be a function handler which returns M\X.
     The M2 combined with M1 defines preconditioner as
     preconditioner=M1*M2.  The X0 is the initial guess, the default
     value is zeros(N,1).

     The value X is a computed result of this procedure.  The value
     FLAG can be 0 when we reach tolerance in MAXIT iterations, 1 when
     we don't reach tolerance in MAXIT iterations and 3 when the
     procedure stagnates.  The value RELRES is a relative residual -
     norm(b-A*x)/norm(b).  The value ITER is an iteration number in
     which x was computed.  The value RESVEC is a vector of RELRES for
     each iteration.


 -- Function File:  cgs (A, B)
 -- Function File:  cgs (A, B, TOL, MAXIT, M1, M2, X0)
     This procedure attempts to solve a system of linear equations A*x
     = b for x.  The A must be square, symmetric and positive definite
     real matrix N*N.  The B must be a one column vector with a length
     of N.  The TOL specifies the tolerance of the method, default
     value is 1e-6.  The MAXIT specifies the maximum number of
     iteration, default value is MIN(20,N).  The M1 specifies a
     preconditioner, can also be a function handler which returns M\X.
     The M2 combined with M1 defines preconditioner as
     preconditioner=M1*M2.  The X0 is initial guess, default value is
     zeros(N,1).



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

19 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'.  This is an iterative technique so a starting point will have
to be provided.  This also has the consequence that convergence is not
guaranteed even if a solution exists.

 -- Function File:  fsolve (FCN, X0, OPTIONS)
 -- Function File: [X, FVEC, INFO, OUTPUT, FJAC] = fsolve (FCN, ...)
     Solve a system of nonlinear equations defined by the function FCN.
     FCN should accept a vector (array) defining the unknown variables,
     and return a vector of left-hand sides of the equations.
     Right-hand sides are defined to be zeros.  In other words, this
     function attempts to determine a vector X such that `FCN (X)'
     gives (approximately) all zeros.  X0 determines a starting guess.
     The shape of X0 is preserved in all calls to FCN, but otherwise it
     is treated as a column vector.  OPTIONS is a structure specifying
     additional options.  Currently, `fsolve' recognizes these options:
     `"FunValCheck"', `"OutputFcn"', `"TolX"', `"TolFun"', `"MaxIter"',
     `"MaxFunEvals"', `"Jacobian"', `"Updating"', `"ComplexEqn"'
     `"TypicalX"', `"AutoScaling"' and `"FinDiffType"'.

     If `"Jacobian"' is `"on"', it specifies that FCN, called with 2
     output arguments, also returns the Jacobian matrix of right-hand
     sides at the requested point.  `"TolX"' specifies the termination
     tolerance in the unknown variables, while `"TolFun"' is a
     tolerance for equations.  Default is `1e-7' for both `"TolX"' and
     `"TolFun"'.

     If `"AutoScaling"' is on, the variables will be automatically
     scaled according to the column norms of the (estimated) Jacobian.
     As a result, TolF becomes scaling-independent.  By default, this
     option is off, because it may sometimes deliver unexpected (though
     mathematically correct) results.

     If `"Updating"' is "on", the function will attempt to use Broyden
     updates to update the Jacobian, in order to reduce the amount of
     Jacobian calculations.  If your user function always calculates
     the Jacobian (regardless of number of output arguments), this
     option provides no advantage and should be set to false.

     `"ComplexEqn"' is `"on"', `fsolve' will attempt to solve complex
     equations in complex variables, assuming that the equations
     possess a complex derivative (i.e., are holomorphic).  If this is
     not what you want, should unpack the real and imaginary parts of
     the system to get a real system.

     For description of the other options, see `optimset'.

     On return, FVAL contains the value of the function FCN evaluated
     at X, and INFO may be one of the following values:

    1
          Converged to a solution point.  Relative residual error is
          less than specified by TolFun.

    2
          Last relative step size was less that TolX.

    3
          Last relative decrease in residual was less than TolF.

    0
          Iteration limit exceeded.

    -3
          The trust region radius became excessively small.

     Note: If you only have a single nonlinear equation of one
     variable, using `fzero' is usually a much better idea.

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

     Note about user-supplied Jacobians: As an inherent property of the
     algorithm, Jacobian is always requested for a solution vector
     whose residual vector is already known, and it is the last
     accepted successful step.  Often this will be one of the last two
     calls, but not always.  If the savings by reusing intermediate
     results from residual calculation in Jacobian calculation are
     significant, the best strategy is to employ OutputFcn: After a
     vector is evaluated for residuals, if OutputFcn is called with
     that vector, then the intermediate results should be saved for
     future Jacobian evaluation, and should be kept until a Jacobian
     evaluation is requested or until outputfcn is called with a
     different vector, in which case they should be dropped in favor of
     this most recent vector.  A short example how this can be achieved
     follows:

          function [fvec, fjac] = user_func (x, optimvalues, state)
          persistent sav = [], sav0 = [];
          if (nargin == 1)
            ## evaluation call
            if (nargout == 1)
              sav0.x = x; # mark saved vector
              ## calculate fvec, save results to sav0.
            elseif (nargout == 2)
              ## calculate fjac using sav.
            endif
          else
            ## outputfcn call.
            if (all (x == sav0.x))
              sav = sav0;
            endif
            ## maybe output iteration status, etc.
          endif
          endfunction

           ....

          fsolve (@user_func, x0, optimset ("OutputFcn", @user_func, ...))

   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 = zeros (2, 1);
       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, fval, info] = fsolve (@f, [1; 2])

results in the solution

     x =

       0.57983
       2.54621

     fval =

       -5.7184e-10
        5.5460e-10

     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

   When no Jacobian is supplied (as in the example above) it is
approximated numerically.  This requires more function evaluations, and
hence is less efficient.  In the example above we could compute the
Jacobian analytically as

     function [y, jac] = f (x)
       y = zeros (2, 1);
       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;
       if (nargout == 2)
         jac = zeros (2, 2);
         jac(1,1) =  3*x(2) - 4*x(1);
         jac(1,2) =  4*cos(x(2)) + 3*x(1);
         jac(2,1) = -2*x(2)^2 - 3*sin(x(1)) + 6*x(1);
         jac(2,2) = -4*x(1)*x(2);
       endif
     endfunction

The Jacobian can then be used with the following call to `fsolve':

     [x, fval, info] = fsolve (@f, [1; 2], optimset ("jacobian", "on"));

which gives the same solution as before.

 -- Function File:  fzero (FUN, X0)
 -- Function File:  fzero (FUN, X0, OPTIONS)
 -- Function File: [X, FVAL, INFO, OUTPUT] = fzero (...)
     Find a zero of a univariate function.

     FUN should be a function handle or name.  X0 should be a
     two-element vector specifying two points which bracket a zero.  In
     other words, there must be a change in sign of the function between
     X0(1) and X0(2).  More mathematically, the following must hold

          sign (FUN(X0(1))) * sign (FUN(X0(2))) <= 0

     If X0 is a single scalar then several nearby and distant values
     are probed in an attempt to obtain a valid bracketing.  If this is
     not successful, the function fails.  OPTIONS is a structure
     specifying additional options.  Currently, `fzero' recognizes
     these options: `"FunValCheck"', `"OutputFcn"', `"TolX"',
     `"MaxIter"', `"MaxFunEvals"'.  For a description of these options,
     see *note optimset: doc-optimset.

     On exit, the function returns X, the approximate zero point and
     FVAL, the function value thereof.  INFO is an exit flag that can
     have these values:

        * 1  The algorithm converged to a solution.

        * 0  Maximum number of iterations or function evaluations has
          been reached.

        * -1 The algorithm has been terminated from user output
          function.

        * -5 The algorithm may have converged to a singular point.

     OUTPUT is a structure containing runtime information about the
     `fzero' algorithm.  Fields in the structure are:

        * iterations  Number of iterations through loop.

        * nfev  Number of function evaluations.

        * bracketx  A two-element vector with the final bracketing of
          the zero along the x-axis.

        * brackety  A two-element vector with the final bracketing of
          the zero along the y-axis.

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


File: octave.info,  Node: Diagonal and Permutation Matrices,  Next: Sparse Matrices,  Prev: Nonlinear Equations,  Up: Top

20 Diagonal and Permutation Matrices
************************************

* Menu:

* Basic Usage::          Creation and Manipulation of Diagonal and Permutation Matrices
* Matrix Algebra::       Linear Algebra with Diagonal and Permutation Matrices
* Function Support::     Functions That Are Aware of These Matrices
* Example Codes::        Some Examples of Usage
* Zeros Treatment::      The Differences in Treatment of Zero Elements


File: octave.info,  Node: Basic Usage,  Next: Matrix Algebra,  Up: Diagonal and Permutation Matrices

20.1 Creating and Manipulating Diagonal and Permutation Matrices
================================================================

A diagonal matrix is defined as a matrix that has zero entries outside
the main diagonal; that is, `D(i,j) == 0' if `i != j'.  Most often,
square diagonal matrices are considered; however, the definition can
equally be applied to non-square matrices, in which case we usually
speak of a rectangular diagonal matrix.

   A permutation matrix is defined as a square matrix that has a single
element equal to unity in each row and each column; all other elements
are zero.  That is, there exists a permutation (vector) `p' such that
`P(i,j) == 1' if `j == p(i)' and `P(i,j) == 0' otherwise.

   Octave provides special treatment of real and complex rectangular
diagonal matrices, as well as permutation matrices.  They are stored as
special objects, using efficient storage and algorithms, facilitating
writing both readable and efficient matrix algebra expressions in the
Octave language.

* Menu:

* Creating Diagonal Matrices::
* Creating Permutation Matrices::
* Explicit and Implicit Conversions::


File: octave.info,  Node: Creating Diagonal Matrices,  Next: Creating Permutation Matrices,  Up: Basic Usage

20.1.1 Creating Diagonal Matrices
---------------------------------

The most common and easiest way to create a diagonal matrix is using the
built-in function "diag".  The expression `diag (v)', with V a vector,
will create a square diagonal matrix with elements on the main diagonal
given by the elements of V, and size equal to the length of V.  `diag
(v, m, n)' can be used to construct a rectangular diagonal matrix.  The
result of these expressions will be a special diagonal matrix object,
rather than a general matrix object.

   Diagonal matrix with unit elements can be created using "eye".  Some
other built-in functions can also return diagonal matrices.  Examples
include "balance" or "inv".

   Example:

       diag (1:4)
     =>
     Diagonal Matrix

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

       diag(1:3,5,3)

     =>
     Diagonal Matrix

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


File: octave.info,  Node: Creating Permutation Matrices,  Next: Explicit and Implicit Conversions,  Prev: Creating Diagonal Matrices,  Up: Basic Usage

20.1.2 Creating Permutation Matrices
------------------------------------

For creating permutation matrices, Octave does not introduce a new
function, but rather overrides an existing syntax: permutation matrices
can be conveniently created by indexing an identity matrix by
permutation vectors.  That is, if Q is a permutation vector of length
N, the expression

       P = eye (n) (:, q);

will create a permutation matrix - a special matrix object.

     eye (n) (q, :)

will also work (and create a row permutation matrix), as well as

     eye (n) (q1, q2).

   For example:

       eye (4) ([1,3,2,4],:)
     =>
     Permutation Matrix

        1   0   0   0
        0   0   1   0
        0   1   0   0
        0   0   0   1

       eye (4) (:,[1,3,2,4])
     =>
     Permutation Matrix

        1   0   0   0
        0   0   1   0
        0   1   0   0
        0   0   0   1

   Mathematically, an identity matrix is both diagonal and permutation
matrix.  In Octave, `eye (n)' returns a diagonal matrix, because a
matrix can only have one class.  You can convert this diagonal matrix
to a permutation matrix by indexing it by an identity permutation, as
shown below.  This is a special property of the identity matrix;
indexing other diagonal matrices generally produces a full matrix.

       eye (3)
     =>
     Diagonal Matrix

        1   0   0
        0   1   0
        0   0   1

       eye(3)(1:3,:)
     =>
     Permutation Matrix

        1   0   0
        0   1   0
        0   0   1

   Some other built-in functions can also return permutation matrices.
Examples include "inv" or "lu".


File: octave.info,  Node: Explicit and Implicit Conversions,  Prev: Creating Permutation Matrices,  Up: Basic Usage

20.1.3 Explicit and Implicit Conversions
----------------------------------------

The diagonal and permutation matrices are special objects in their own
right.  A number of operations and built-in functions are defined for
these matrices to use special, more efficient code than would be used
for a full matrix in the same place.  Examples are given in further
sections.

   To facilitate smooth mixing with full matrices, backward
compatibility, and compatibility with MATLAB, the diagonal and
permutation matrices should allow any operation that works on full
matrices, and will either treat it specially, or implicitly convert
themselves to full matrices.

   Instances include matrix indexing, except for extracting a single
element or a leading submatrix, indexed assignment, or applying most
mapper functions, such as "exp".

   An explicit conversion to a full matrix can be requested using the
built-in function "full".  It should also be noted that the diagonal
and permutation matrix objects will cache the result of the conversion
after it is first requested (explicitly or implicitly), so that
subsequent conversions will be very cheap.


File: octave.info,  Node: Matrix Algebra,  Next: Function Support,  Prev: Basic Usage,  Up: Diagonal and Permutation Matrices

20.2 Linear Algebra with Diagonal and Permutation Matrices
==========================================================

As has been already said, diagonal and permutation matrices make it
possible to use efficient algorithms while preserving natural linear
algebra syntax.  This section describes in detail the operations that
are treated specially when performed on these special matrix objects.

* Menu:

* Expressions Involving Diagonal Matrices::
* Expressions Involving Permutation Matrices::


File: octave.info,  Node: Expressions Involving Diagonal Matrices,  Next: Expressions Involving Permutation Matrices,  Up: Matrix Algebra

20.2.1 Expressions Involving Diagonal Matrices
----------------------------------------------

Assume D is a diagonal matrix.  If M is a full matrix, then `D*M' will
scale the rows of M.  That means, if `S = D*M', then for each pair of
indices i,j it holds

     S(i,j) = D(i,i) * M(i,j).

   Similarly, `M*D' will do a column scaling.

   The matrix D may also be rectangular, m-by-n where `m != n'.  If `m
< n', then the expression `D*M' is equivalent to

     D(:,1:m) * M(1:m,:),

i.e., trailing `n-m' rows of M are ignored.  If `m > n', then `D*M' is
equivalent to

     [D(1:n,n) * M; zeros(m-n, columns (M))],

i.e., null rows are appended to the result.  The situation for
right-multiplication `M*D' is analogous.

   The expressions `D \ M' and `M / D' perform inverse scaling.  They
are equivalent to solving a diagonal (or rectangular diagonal) in a
least-squares minimum-norm sense.  In exact arithmetic, this is
equivalent to multiplying by a pseudoinverse.  The pseudoinverse of a
rectangular diagonal matrix is again a rectangular diagonal matrix with
swapped dimensions, where each nonzero diagonal element is replaced by
its reciprocal.  The matrix division algorithms do, in fact, use
division rather than multiplication by reciprocals for better numerical
accuracy; otherwise, they honor the above definition.  Note that a
diagonal matrix is never truncated due to ill-conditioning; otherwise,
it would not be much useful for scaling.  This is typically consistent
with linear algebra needs.  A full matrix that only happens to be
diagonal (an is thus not a special object) is of course treated
normally.

   Multiplication and division by diagonal matrices works efficiently
also when combined with sparse matrices, i.e., `D*S', where D is a
diagonal matrix and S is a sparse matrix scales the rows of the sparse
matrix and returns a sparse matrix.  The expressions `S*D', `D\S', `S/D'
work analogically.

   If D1 and D2 are both diagonal matrices, then the expressions

     D1 + D2
     D1 - D2
     D1 * D2
     D1 / D2
     D1 \ D2

again produce diagonal matrices, provided that normal dimension
matching rules are obeyed.  The relations used are same as described
above.

   Also, a diagonal matrix D can be multiplied or divided by a scalar,
or raised to a scalar power if it is square, producing diagonal matrix
result in all cases.

   A diagonal matrix can also be transposed or conjugate-transposed,
giving the expected result.  Extracting a leading submatrix of a
diagonal matrix, i.e., `D(1:m,1:n)', will produce a diagonal matrix,
other indexing expressions will implicitly convert to full matrix.

   Adding a diagonal matrix to a full matrix only operates on the
diagonal elements.  Thus,

     A = A + eps * eye (n)

is an efficient method of augmenting the diagonal of a matrix.
Subtraction works analogically.

   When involved in expressions with other element-by-element
operators, `.*', `./', `.\' or `.^', an implicit conversion to full
matrix will take place.  This is not always strictly necessary but
chosen to facilitate better consistency with MATLAB.


File: octave.info,  Node: Expressions Involving Permutation Matrices,  Prev: Expressions Involving Diagonal Matrices,  Up: Matrix Algebra

20.2.2 Expressions Involving Permutation Matrices
-------------------------------------------------

If P is a permutation matrix and M a matrix, the expression `P*M' will
permute the rows of M.  Similarly, `M*P' will yield a column
permutation.  Matrix division `P\M' and `M/P' can be used to do inverse
permutation.

   The previously described syntax for creating permutation matrices
can actually help an user to understand the connection between a
permutation matrix and a permuting vector.  Namely, the following
holds, where `I = eye (n)' is an identity matrix:

       I(p,:) * M = (I*M) (p,:) = M(p,:)

   Similarly,

       M * I(:,p) = (M*I) (:,p) = M(:,p)

   The expressions `I(p,:)' and `I(:,p)' are permutation matrices.

   A permutation matrix can be transposed (or conjugate-transposed,
which is the same, because a permutation matrix is never complex),
inverting the permutation, or equivalently, turning a row-permutation
matrix into a column-permutation one.  For permutation matrices,
transpose is equivalent to inversion, thus `P\M' is equivalent to
`P'*M'.  Transpose of a permutation matrix (or inverse) is a
constant-time operation, flipping only a flag internally, and thus the
choice between the two above equivalent expressions for inverse
permuting is completely up to the user's taste.

   Multiplication and division by permutation matrices works
efficiently also when combined with sparse matrices, i.e., `P*S', where
P is a permutation matrix and S is a sparse matrix permutes the rows of
the sparse matrix and returns a sparse matrix.  The expressions `S*P',
`P\S', `S/P' work analogically.

   Two permutation matrices can be multiplied or divided (if their
sizes match), performing a composition of permutations.  Also a
permutation matrix can be indexed by a permutation vector (or two
vectors), giving again a permutation matrix.  Any other operations do
not generally yield a permutation matrix and will thus trigger the
implicit conversion.


File: octave.info,  Node: Function Support,  Next: Example Codes,  Prev: Matrix Algebra,  Up: Diagonal and Permutation Matrices

20.3 Functions That Are Aware of These Matrices
===============================================

This section lists the built-in functions that are aware of diagonal and
permutation matrices on input, or can return them as output.  Passed to
other functions, these matrices will in general trigger an implicit
conversion.  (Of course, user-defined dynamically linked functions may
also work with diagonal or permutation matrices).

* Menu:

* Diagonal Matrix Functions::
* Permutation Matrix Functions::


File: octave.info,  Node: Diagonal Matrix Functions,  Next: Permutation Matrix Functions,  Up: Function Support

20.3.1 Diagonal Matrix Functions
--------------------------------

"inv" and "pinv" can be applied to a diagonal matrix, yielding again a
diagonal matrix.  "det" will use an efficient straightforward
calculation when given a diagonal matrix, as well as "cond".  The
following mapper functions can be applied to a diagonal matrix without
converting it to a full one: "abs", "real", "imag", "conj", "sqrt".  A
diagonal matrix can also be returned from the "balance" and "svd"
functions.  The "sparse" function will convert a diagonal matrix
efficiently to a sparse matrix.


File: octave.info,  Node: Permutation Matrix Functions,  Prev: Diagonal Matrix Functions,  Up: Function Support

20.3.2 Permutation Matrix Functions
-----------------------------------

"inv" and "pinv" will invert a permutation matrix, preserving its
specialness.  "det" can be applied to a permutation matrix, efficiently
calculating the sign of the permutation (which is equal to the
determinant).

   A permutation matrix can also be returned from the built-in functions
"lu" and "qr", if a pivoted factorization is requested.

   The "sparse" function will convert a permutation matrix efficiently
to a sparse matrix.  The "find" function will also work efficiently
with a permutation matrix, making it possible to conveniently obtain
the permutation indices.


File: octave.info,  Node: Example Codes,  Next: Zeros Treatment,  Prev: Function Support,  Up: Diagonal and Permutation Matrices

20.4 Some Examples of Usage
===========================

The following can be used to solve a linear system `A*x = b' using the
pivoted LU factorization:

       [L, U, P] = lu (A); ## now L*U = P*A
       x = U \ L \ P*b;

This is how you normalize columns of a matrix X to unit norm:

       s = norm (X, "columns");
       X = diag (s) \ X;

The following expression is a way to efficiently calculate the sign of a
permutation, given by a permutation vector P.  It will also work in
earlier versions of Octave, but slowly.

       det (eye (length (p))(p, :))

Finally, here's how you solve a linear system `A*x = b' with Tikhonov
regularization (ridge regression) using SVD (a skeleton only):

       m = rows (A); n = columns (A);
       [U, S, V] = svd (A);
       ## determine the regularization factor alpha
       ## alpha = ...
       ## transform to orthogonal basis
       b = U'*b;
       ## Use the standard formula, replacing A with S.
       ## S is diagonal, so the following will be very fast and accurate.
       x = (S'*S + alpha^2 * eye (n)) \ (S' * b);
       ## transform to solution basis
       x = V*x;


File: octave.info,  Node: Zeros Treatment,  Prev: Example Codes,  Up: Diagonal and Permutation Matrices

20.5 The Differences in Treatment of Zero Elements
==================================================

Making diagonal and permutation matrices special matrix objects in
their own right and the consequent usage of smarter algorithms for
certain operations implies, as a side effect, small differences in
treating zeros.  The contents of this section applies also to sparse
matrices, discussed in the following chapter.

   The IEEE standard defines the result of the expressions `0*Inf' and
`0*NaN' as `NaN', as it has been generally agreed that this is the best
compromise.  Numerical software dealing with structured and sparse
matrices (including Octave) however, almost always makes a distinction
between a "numerical zero" and an "assumed zero".  A "numerical zero"
is a zero value occurring in a place where any floating-point value
could occur.  It is normally stored somewhere in memory as an explicit
value.  An "assumed zero", on the contrary, is a zero matrix element
implied by the matrix structure (diagonal, triangular) or a sparsity
pattern; its value is usually not stored explicitly anywhere, but is
implied by the underlying data structure.

   The primary distinction is that an assumed zero, when multiplied by
any number, or divided by any nonzero number, yields *always* a zero,
even when, e.g., multiplied by `Inf' or divided by `NaN'.  The reason
for this behavior is that the numerical multiplication is not actually
performed anywhere by the underlying algorithm; the result is just
assumed to be zero.  Equivalently, one can say that the part of the
computation involving assumed zeros is performed symbolically, not
numerically.

   This behavior not only facilitates the most straightforward and
efficient implementation of algorithms, but also preserves certain
useful invariants, like:
   * scalar * diagonal matrix is a diagonal matrix

   * sparse matrix / scalar preserves the sparsity pattern

   * permutation matrix * matrix is equivalent to permuting rows
   all of these natural mathematical truths would be invalidated by
treating assumed zeros as numerical ones.

   Note that MATLAB does not strictly follow this principle and converts
assumed zeros to numerical zeros in certain cases, while not doing so in
other cases.  As of today, there are no intentions to mimic such
behavior in Octave.

   Examples of effects of assumed zeros vs. numerical zeros:

     Inf * eye (3)
     =>
        Inf     0     0
          0   Inf     0
          0     0   Inf

     Inf * speye (3)
     =>
     Compressed Column Sparse (rows = 3, cols = 3, nnz = 3 [33%])

       (1, 1) -> Inf
       (2, 2) -> Inf
       (3, 3) -> Inf

     Inf * full (eye (3))
     =>
        Inf   NaN   NaN
        NaN   Inf   NaN
        NaN   NaN   Inf

     diag(1:3) * [NaN; 1; 1]
     =>
        NaN
          2
          3

     sparse(1:3,1:3,1:3) * [NaN; 1; 1]
     =>
        NaN
          2
          3
     [1,0,0;0,2,0;0,0,3] * [NaN; 1; 1]
     =>
        NaN
        NaN
        NaN


File: octave.info,  Node: Sparse Matrices,  Next: Numerical Integration,  Prev: Diagonal and Permutation Matrices,  Up: Top

21 Sparse Matrices
******************

* Menu:

* Basics::                      Creation and Manipulation of Sparse Matrices
* Sparse Linear Algebra::       Linear Algebra on Sparse Matrices
* Iterative Techniques::        Iterative Techniques
* Real Life Example::           Using Sparse Matrices


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

21.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 of 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 does 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.

* Menu:

* Storage of Sparse Matrices::
* Creating Sparse Matrices::
* Information::
* Operators and Functions::


File: octave.info,  Node: Storage of Sparse Matrices,  Next: Creating Sparse Matrices,  Up: Basics

21.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
complexity 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 their 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 the 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 simplification in the code, in that there 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, 1, 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 at zero, while in Octave itself
the row and column indexing starts at one.  Thus the number of elements
in the I-th column is given by `CIDX (I + 1) - CIDX (I)'.

   Although Octave uses a compressed column format, 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, which makes certain operations faster.  However, it imposes
the need to sort the elements on the creation of sparse matrices.
Having disordered 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) Y. Saad "SPARSKIT: A basic toolkit for sparse matrix
computation", 1994,
`http://www-users.cs.umn.edu/~saad/software/SPARSKIT/paper.ps'


File: octave.info,  Node: Creating Sparse Matrices,  Next: Information,  Prev: Storage of Sparse Matrices,  Up: Basics

21.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", "diag", 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 normal random distributions of elements.
They have exactly the same calling convention, where `sprand (R, C, D)',
creates an R-by-C sparse matrix with a density of filled elements of D.

   Other functions of interest that directly create sparse matrices, are
"diag" 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 = diag (sparse(randn(1,n)), -1);

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

 -- 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 `diag'.  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 represent 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


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

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

     *See also:* *note arrayfun: doc-arrayfun, *note cellfun:
     doc-cellfun, *note structfun: doc-structfun.

 -- Function File: R = spones (S)
     Replace the non-zero entries of S with ones.  This creates a
     sparse matrix with the same structure as S.

 -- 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 uniformly distributed between 0 and 1.

     Note: sometimes the actual density may be a bit smaller than D.
     This is unlikely to happen for large, truly sparse, matrices.

     If called with a single matrix argument, a random sparse matrix is
     generated wherever the matrix S is non-zero.

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

 -- Function File:  sprandn (M, N, D)
 -- Function File:  sprandn (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.

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

 -- Function File:  sprandsym (N, D)
 -- Function File:  sprandsym (S)
     Generate a symmetric random sparse matrix.  The size of the matrix
     will be N 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 in its lower
     triangular part.

     *See also:* *note sprand: doc-sprand, *note sprandn: doc-sprandn.

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

       ri = ci = d = [];
       for j = 1:c
         ri = [ri; randperm(r)(1:n)'];
         ci = [ci; j*ones(n,1)];
         d = [d; rand(n,1)];
       endfor
       s = sparse (ri, ci, d, r, c);

creates an R-by-C sparse matrix with a random distribution of N (<R)
elements per column.  The elements of the vectors do not need to be
sorted in any particular order as Octave will sort them prior to
storing the data.  However, pre-sorting the data will make the 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 of the above loop.
Therefore the "spalloc" function ignores the NZ argument and does not
pre-assign the memory for the matrix.  Therefore, it is vitally
important that code using to above structure should be vectorized as
much as possible to minimize the number of assignments and reduce the
number of memory allocations.

 -- Loadable Function: FM = full (SM)
     returns a full storage matrix from a sparse, diagonal, permutation
     matrix or a range.

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

 -- Loadable Function: S = spalloc (M, N, NZ)
     Create an M-by-N sparse matrix with pre-allocated space for at
     most NZ nonzero elements.  This is useful for building the matrix
     incrementally by a sequence of indexed assignments.  Subsequent
     indexed assignments will reuse the pre-allocated memory, provided
     they are of one of the simple forms

        * `S(I:J) = X'

        * `S(:,I:J) = X'

        * `S(K:L,I:J) = X'

     and that the following conditions are met:

        * the assignment does not decrease nnz(S).

        * after the assignment, nnz(S) does not exceed NZ.

        * no index is out of bounds.

     Partial movement of data may still occur, but in general the
     assignment will be more memory and time-efficient under these
     circumstances.  In particular, it is possible to efficiently build
     a pre-allocated sparse matrix from contiguous block of columns.

     The amount of pre-allocated memory for a given matrix may be
     queried using the function `nzmax'.

     *See also:* *note nzmax: doc-nzmax, *note sparse: doc-sparse.

 -- Loadable Function: S = sparse (A)
 -- Loadable Function: S = sparse (I, J, SV, M, N, NZMAX)
 -- Loadable Function: S = sparse (I, J, SV)
 -- Loadable Function: S = sparse (I, J, S, M, N, "unique")
 -- Loadable Function: S = sparse (M, N)
     Create a sparse matrix from the full matrix or row, column, value
     triplets.  If A is a full matrix, convert it to a sparse matrix
     representation, removing all zero values in the process.

     Given the integer index vectors I and J, a 1-by-`nnz' vector of
     real of complex values SV, overall dimensions M and N of the
     sparse matrix.  The argument `nzmax' is ignored but accepted for
     compatibility with MATLAB.  If M or N are not specified their
     values are derived from the maximum index in the vectors I and J
     as given by `M = max (I)', `N = max (J)'.

     *Note*: if multiple values are specified with the same I, J
     indices, the corresponding values in S will be added.

     The following are all equivalent:

          s = sparse (i, j, s, m, n)
          s = sparse (i, j, s, m, n, "summation")
          s = sparse (i, j, s, m, n, "sum")

     Given the option "unique". if more than two values are specified
     for the same I, J indices, the last specified value will be used.

     `sparse(M, N)' is equivalent to `sparse ([], [], [], M, N, 0)'

     If any of SV, I or J are scalars, they are expanded to have a
     common size.

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

 -- 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 imaginary part can
     be used to force a particular matrix size.

   The above problem of memory reallocation can be avoided in
oct-files.  However, the construction of a sparse matrix from an
oct-file is more complex than can be discussed here, and you are
referred to chapter *note Dynamically Linked Functions::, to have a
full description of the techniques involved.


File: octave.info,  Node: Information,  Next: Operators and Functions,  Prev: Creating Sparse Matrices,  Up: Basics

21.1.3 Finding out Information about Sparse Matrices
----------------------------------------------------

There are a number of functions that allow information concerning
sparse matrices to be obtained.  The most basic of these is "issparse"
that identifies whether a particular Octave object is in fact a sparse
matrix.

   Another very basic function is "nnz" that returns the number of
non-zero entries there are in a sparse matrix, while the function
"nzmax" returns the amount of storage allocated to the sparse matrix.
Note that Octave tends to crop unused memory at the first opportunity
for sparse objects.  There are some cases of user created sparse
objects where the value returned by "nzmax" will not be the same as
"nnz", but in general they will give the same result.  The function
"spstats" returns some basic statistics on the columns of a sparse
matrix including the number of elements, the mean and the variance of
each column.

 -- Loadable Function:  issparse (X)
     Return true if X is a sparse matrix.

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

 -- Built-in Function: SCALAR = nnz (A)
     Return the number of non zero elements in A.

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

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

 -- Built-in 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
     opportunity for sparse objects.  There are some cases of user
     created sparse objects where the value returned by "nzmax" will
     not be the same as "nnz", but in general they will give the same
     result.

     *See also:* *note sparse: doc-sparse, *note spalloc: doc-spalloc.

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

   When solving linear equations involving sparse matrices Octave
determines the means to solve the equation based on the type of the
matrix as discussed in *note Sparse Linear Algebra::.  Octave probes the
matrix type when the div (/) or ldiv (\) operator is first used with
the matrix and then caches the type.  However the "matrix_type"
function can be used to determine the type of the sparse matrix prior
to use of the div or ldiv operators.  For example,

     a = tril (sprandn(1024, 1024, 0.02), -1) ...
         + speye(1024);
     matrix_type (a);
     ans = Lower

shows that Octave correctly determines the matrix type for lower
triangular matrices.  "matrix_type" can also be used to force the type
of a matrix to be a particular type.  For example:

     a = matrix_type (tril (sprandn (1024, ...
        1024, 0.02), -1) + speye(1024), 'Lower');

   This allows the cost of determining the matrix type to be avoided.
However, 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 identify the matrix type

   There are several graphical means of finding out information about
sparse matrices.  The first is the "spy" command, which displays the
structure of the non-zero elements of the matrix.  *Note
fig:spmatrix::, for an example of the use of "spy".  More advanced
graphical information can be obtained with the "treeplot", "etreeplot"
and "gplot" commands.


            |  * *
            |  * * * *
            |    * *   * *
            |    *   *     * *
          5 -      *   *       * *
            |      *     *         * *
            |        *     *           * *
            |        *       *             *
            |          *       *
         10 -          *         *
            |            *         *
            |            *           *
            |              *           *
            |              *             *
         15 -                *             *
            |----------|---------|---------|
                       5        10        15
Figure 21.1: Structure of simple sparse matrix.

   One use of sparse matrices is in graph theory, where the
interconnections between nodes are represented as an adjacency matrix.
That is, if the i-th node in a graph is connected to the j-th node.
Then the ij-th node (and in the case of undirected graphs the ji-th
node) of the sparse adjacency matrix is non-zero.  If each node is then
associated with a set of coordinates, then the "gplot" command can be
used to graphically display the interconnections between nodes.

   As a trivial example of the use of "gplot" consider the example,

     A = sparse([2,6,1,3,2,4,3,5,4,6,1,5],
         [1,1,2,2,3,3,4,4,5,5,6,6],1,6,6);
     xy = [0,4,8,6,4,2;5,0,5,7,5,7]';
     gplot(A,xy)

which creates an adjacency matrix `A' where node 1 is connected to
nodes 2 and 6, node 2 with nodes 1 and 3, etc.  The coordinates of the
nodes are given in the n-by-2 matrix `xy'.

   The dependencies between the nodes of a Cholesky factorization can be
calculated in linear time without explicitly needing to calculate the
Cholesky factorization by the `etree' command.  This command returns
the elimination tree of the matrix and can be displayed graphically by
the command `treeplot(etree(A))' if `A' is symmetric or
`treeplot(etree(A+A'))' otherwise.

 -- Function File:  spy (X)
 -- Function File:  spy (..., MARKERSIZE)
 -- Function File:  spy (..., LINE_SPEC)
     Plot the sparsity pattern of the sparse matrix X.  If the argument
     MARKERSIZE is given as an scalar value, it is used to determine the
     point size in the plot.  If the string LINE_SPEC is given it is
     passed to `plot' and determines the appearance of the plot.

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

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

 -- Function File:  etreeplot (A)
 -- Function File:  etreeplot (A, NODE_STYLE, EDGE_STYLE)
     Plot the elimination tree of the matrix A or `A+A'' if A in not
     symmetric.  The optional parameters NODE_STYLE and EDGE_STYLE
     define the output style.

     *See also:* *note treeplot: doc-treeplot, *note gplot: doc-gplot.

 -- Function File:  gplot (A, XY)
 -- Function File:  gplot (A, XY, LINE_STYLE)
 -- Function File: [X, Y] = gplot (A, XY)
     Plot a graph defined by A and XY in the graph theory sense.  A is
     the adjacency matrix of the array to be plotted and XY is an
     N-by-2 matrix containing the coordinates of the nodes of the graph.

     The optional parameter LINE_STYLE defines the output style for the
     plot.  Called with no output arguments the graph is plotted
     directly.  Otherwise, return the coordinates of the plot in X and
     Y.

     *See also:* *note treeplot: doc-treeplot, *note etreeplot:
     doc-etreeplot, *note spy: doc-spy.

 -- Function File:  treeplot (TREE)
 -- Function File:  treeplot (TREE, NODE_STYLE, EDGE_STYLE)
     Produces a graph of tree or forest.  The first argument is vector
     of predecessors, optional parameters NODE_STYLE and EDGE_STYLE
     define the output style.  The complexity of the algorithm is O(n)
     in terms of is time and memory requirements.

     *See also:* *note etreeplot: doc-etreeplot, *note gplot: doc-gplot.

 -- Function File:  treelayout (TREE)
 -- Function File:  treelayout (TREE, PERMUTATION)
     treelayout lays out a tree or a forest.  The first argument TREE
     is a vector of predecessors, optional parameter PERMUTATION is an
     optional postorder permutation.  The complexity of the algorithm
     is O(n) in terms of time and memory requirements.

     *See also:* *note etreeplot: doc-etreeplot, *note gplot:
     doc-gplot, *note treeplot: doc-treeplot.


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

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

* Menu:

* Sparse Functions::
* Return Types of Operators and Functions::
* Mathematical Considerations::


File: octave.info,  Node: Sparse Functions,  Next: Return Types of Operators and Functions,  Up: Operators and Functions

21.1.4.1 Sparse Functions
.........................

Many Octave functions have been overloaded to work with either sparse
or full matrices.  There is no difference in calling convention when
using an overloaded function with a sparse matrix, however, there is
also no access to potentially sparse-specific features.  At any time
the sparse matrix specific version of a function can be used by
explicitly calling its function name.

   The table below lists all of the sparse functions of Octave.  Note
that the names of the specific sparse forms of the functions are
typically the same as the general versions with a "sp" prefix.  In the
table below, and in the rest of this article, the specific sparse
versions of functions are used.

Generate sparse matrices:
     "spalloc", "spdiags", "speye", "sprand",   "sprandn", "sprandsym"

Sparse matrix conversion:
     "full", "sparse", "spconvert"

Manipulate sparse matrices
     "issparse", "nnz", "nonzeros", "nzmax",   "spfun", "spones", "spy"

Graph Theory:
     "etree", "etreeplot", "gplot",   "treeplot"

Sparse matrix reordering:
     "amd", "ccolamd", "colamd", "colperm", "csymamd",   "dmperm",
     "symamd", "randperm", "symrcm"

Linear algebra:
     "condest", "eigs", "matrix_type", "normest", "sprank",
     "spaugment", "svds"

Iterative techniques:
     "luinc", "pcg", "pcr"

Miscellaneous:
     "spparms", "symbfact", "spstats"

   In addition all of the standard Octave mapper functions (i.e., basic
math functions that take a single argument) such as "abs", etc.  can
accept sparse matrices.  The reader is referred to the documentation
supplied with these functions within Octave itself for further details.


File: octave.info,  Node: Return Types of Operators and Functions,  Next: Mathematical Considerations,  Prev: Sparse Functions,  Up: Operators and Functions

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

The two basic reasons 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 number of 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, if `sparse_auto_mutate' is true, 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 are 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 behavior 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.

 -- Built-in Function: VAL = sparse_auto_mutate ()
 -- Built-in Function: OLD_VAL = sparse_auto_mutate (NEW_VAL)
     Query or set the internal variable that controls whether Octave
     will automatically mutate sparse matrices to real matrices to save
     memory.  For example:

          s = speye(3);
          sparse_auto_mutate (false)
          s (:, 1) = 1;
          typeinfo (s)
          => sparse matrix
          sparse_auto_mutate (true)
          s (1, :) = 1;
          typeinfo (s)
          => matrix

   Note that the `sparse_auto_mutate' option is incompatible with
MATLAB, and so it is off by default.


File: octave.info,  Node: Mathematical Considerations,  Prev: Return Types of Operators and Functions,  Up: Operators and Functions

21.1.4.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 large
number of terms `0 .^ 0' which is 1. There `S .^ S' is a full matrix.

   Likewise `S .^ -2' involves 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 behavior 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 behavior 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 efficiency, and so the user is warned that calculations
where the sign-bit of zero is important must not be done using sparse
matrices.

   In general any function or operator used on a sparse matrix will
result in a sparse matrix with the same or a larger number of non-zero
elements than the original matrix.  This is particularly true for the
important case of sparse matrix factorizations.  The usual way to
address this is to reorder the matrix, such that its factorization is
sparser than the factorization of the original matrix.  That is the
factorization of `L * U = P * S * Q' has sparser terms `L' and `U' than
the equivalent factorization `L * U = S'.

   Several functions are available to reorder depending on the type of
the matrix to be factorized.  If the matrix is symmetric
positive-definite, then "symamd" or "csymamd" should be used.  Otherwise
"amd", "colamd" or "ccolamd" should be used.  For completeness the
reordering functions "colperm" and "randperm" are also available.

   *Note fig:simplematrix::, for an example of the structure of a simple
positive definite matrix.


            |  * *
            |  * * * *
            |    * *   * *
            |    *   *     * *
          5 -      *   *       * *
            |      *     *         * *
            |        *     *           * *
            |        *       *             *
            |          *       *
         10 -          *         *
            |            *         *
            |            *           *
            |              *           *
            |              *             *
         15 -                *             *
            |----------|---------|---------|
                       5        10        15
Figure 21.2: Structure of simple sparse matrix.

   The standard Cholesky factorization of this matrix can be obtained
by the same command that would be used for a full matrix.  This can be
visualized with the command `r = chol(A); spy(r);'.  *Note
fig:simplechol::.  The original matrix had 43 non-zero terms, while
this Cholesky factorization has 71, with only half of the symmetric
matrix being stored.  This is a significant level of fill in, and
although not an issue for such a small test case, can represents a
large overhead in working with other sparse matrices.

   The appropriate sparsity preserving permutation of the original
matrix is given by "symamd" and the factorization using this reordering
can be visualized using the command `q = symamd(A); r = chol(A(q,q));
spy(r)'.  This gives 29 non-zero terms which is a significant
improvement.

   The Cholesky factorization itself can be used to determine the
appropriate sparsity preserving reordering of the matrix during the
factorization, In that case this might be obtained with three return
arguments as r`[r, p, q] = chol(A); spy(r)'.


            |  * *
            |    * * *
            |      * * * *
            |        * * * * *
          5 -          * * * * * *
            |            * * * * * * *
            |              * * * * * * * *
            |                * * * * * * * *
            |                  * * * * * * *
         10 -                    * * * * * *
            |                      * * * * *
            |                        * * * *
            |                          * * *
            |                            * *
         15 -                              *
            |----------|---------|---------|
                       5        10        15
Figure 21.3: Structure of the un-permuted Cholesky factorization of the
above matrix.


            |  * *
            |    *       *
            |      *   *
            |        * *
          5 -          * *
            |            *                 *
            |              *   *
            |                * *
            |                  *       *
         10 -                    *   *
            |                      * *
            |                        * *
            |                          *   *
            |                            * *
         15 -                              *
            |----------|---------|---------|
                       5        10        15
Figure 21.4: Structure of the permuted Cholesky factorization of the
above matrix.

   In the case of an asymmetric matrix, the appropriate sparsity
preserving permutation is "colamd" and the factorization using this
reordering can be visualized using the command `q = colamd(A); [l, u,
p] = lu(A(:,q)); spy(l+u)'.

   Finally, Octave implicitly reorders the matrix when using the div (/)
and ldiv (\) operators, and so no the user does not need to explicitly
reorder the matrix to maximize performance.

 -- Loadable Function: P = amd (S)
 -- Loadable Function: P = amd (S, OPTS)
     Returns the approximate minimum degree permutation of a matrix.
     This permutation such that the Cholesky factorization of `S (P,
     P)' tends to be sparser than the Cholesky factorization of S
     itself.  `amd' is typically faster than `symamd' but serves a
     similar purpose.

     The optional parameter OPTS is a structure that controls the
     behavior of `amd'.  The fields of the structure are

    OPTS.dense
          Determines what `amd' considers to be a dense row or column
          of the input matrix.  Rows or columns with more than `max(16,
          (dense * sqrt (N)' entries, where N is the order of the
          matrix S, are ignored by `amd' during the calculation of the
          permutation The value of dense must be a positive scalar and
          its default value is 10.0

    OPTS.aggressive
          If this value is a non zero scalar, then `amd' performs
          aggressive absorption.  The default is not to perform
          aggressive absorption.

     The author of the code itself is Timothy A. Davis
     <davis@cise.ufl.edu>, University of Florida (see
     `http://www.cise.ufl.edu/research/sparse/amd').

     *See also:* *note symamd: doc-symamd, *note colamd: doc-colamd.

 -- Loadable Function: P = ccolamd (S)
 -- Loadable Function: P = ccolamd (S, KNOBS)
 -- Loadable Function: P = ccolamd (S, KNOBS, CMEMBER)
 -- Loadable Function: [P, STATS] = ccolamd (...)
     Constrained column approximate minimum degree permutation.  `P =
     ccolamd (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.
     `chol (S(:, P)' * S(:, P))' also tends to be sparser than `chol
     (S' * S)'.  `P = ccolamd (S, 1)' optimizes the ordering for `lu
     (S(:, P))'.  The ordering is followed by a column elimination tree
     post-ordering.

     KNOBS is an optional 1-element to 5-element input vector, with a
     default value of `[0 10 10 1 0]' if not present or empty.  Entries
     not present are set to their defaults.

    `KNOBS(1)'
          if nonzero, the ordering is optimized for `lu (S(:, p))'.  It
          will be a poor ordering for `chol (S(:, P)' * S(:, P))'.
          This is the most important knob for ccolamd.

    `KNOBS(2)'
          if S is m-by-n, rows with more than `max (16, KNOBS(2) * sqrt
          (n))' entries are ignored.

    `KNOBS(3)'
          columns with more than `max (16, KNOBS(3) * sqrt (min (M,
          N)))' entries are ignored and ordered last in the output
          permutation (subject to the cmember constraints).

    `KNOBS(4)'
          if nonzero, aggressive absorption is performed.

    `KNOBS(5)'
          if nonzero, statistics and knobs are printed.


     CMEMBER is an optional vector of length n.  It defines the
     constraints on the column ordering.  If `CMEMBER(j) = C', then
     column J is in constraint set C (C must be in the range 1 to n).
     In the output permutation P, all columns in set 1 appear first,
     followed by all columns in set 2, and so on.  `CMEMBER =
     ones(1,n)' if not present or empty.  `ccolamd (S, [], 1 : n)'
     returns `1 : n'

     `P = ccolamd (S)' is about the same as `P = colamd (S)'.  KNOBS
     and its default values differ.  `colamd' always does aggressive
     absorption, and it finds an ordering suitable for both `lu (S(:,
     P))' and `chol (S(:, P)' * S(:, P))'; it cannot optimize its
     ordering for `lu (S(:, P))' to the extent that `ccolamd (S, 1)'
     can.

     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 CCOLAMD and `STATS(3)' is the number of garbage
     collections performed on the internal data structure used by
     CCOLAMD (roughly of size `2.2 * nnz (S) + 4 * M + 7 * N' integers).

     `STATS(4 : 7)' provide information if CCOLAMD 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 CCOLAMD (reserved for future use).

     The authors of the code itself are S. Larimore, T. Davis (Univ. of
     Florida) and S. Rajamanickam in collaboration with J. Bilbert and
     E. Ng.  Supported by the National Science Foundation (DMS-9504974,
     DMS-9803599, CCR-0203270), and a grant from Sandia National Lab.
     See `http://www.cise.ufl.edu/research/sparse' for ccolamd,
     csymamd, amd, colamd, symamd, and other related orderings.

     *See also:* *note colamd: doc-colamd, *note csymamd: doc-csymamd.

 -- 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 one- to three-element input vector.  If S is
     m-by-n, then rows with more than `max(16,KNOBS(1)*sqrt(n))'
     entries are ignored.  Columns with more than
     `max(16,KNOBS(2)*sqrt(min(m,n)))' entries are removed prior to
     ordering, and ordered last in the output permutation P.  Only
     completely dense rows or columns are removed if `KNOBS(1)' and
     `KNOBS(2)' are < 0, respectively.  If `KNOBS(3)' is nonzero, STATS
     and KNOBS are printed.  The default is `KNOBS = [10 10 0]'.  Note
     that KNOBS differs from earlier versions of colamd

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

     *See also:* *note colperm: doc-colperm, *note symamd: doc-symamd,
     *note ccolamd: doc-ccolamd.

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

 -- Loadable Function: P = csymamd (S)
 -- Loadable Function: P = csymamd (S, KNOBS)
 -- Loadable Function: P = csymamd (S, KNOBS, CMEMBER)
 -- Loadable Function: [P, STATS] = csymamd (...)
     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 `csymamd' 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.  The ordering is followed by an elimination tree
     post-ordering.

     KNOBS is an optional 1-element to 3-element input vector, with a
     default value of `[10 1 0]' if present or empty.  Entries not
     present are set to their defaults.

    `KNOBS(1)'
          If S is n-by-n, then rows and columns with more than
          `max(16,KNOBS(1)*sqrt(n))' entries are ignored, and ordered
          last in the output permutation (subject to the cmember
          constraints).

    `KNOBS(2)'
          If nonzero, aggressive absorption is performed.

    `KNOBS(3)'
          If nonzero, statistics and knobs are printed.


     CMEMBER is an optional vector of length n. It defines the
     constraints on the ordering.  If `CMEMBER(j) = S', then row/column
     j is in constraint set C (C must be in the range 1 to n).  In the
     output permutation P, rows/columns in set 1 appear first, followed
     by all rows/columns in set 2, and so on.  `CMEMBER = ones(1,n)' if
     not present or empty.  `csymamd(S,[],1:n)' returns `1:n'.

     `P = csymamd(S)' is about the same as `P = symamd(S)'.  KNOBS and
     its default values differ.

     `STATS(4:7)' provide information if CCOLAMD 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
     CCOLAMD (reserved for future use).

     The authors of the code itself are S. Larimore, T. Davis (Uni of
     Florida) and S. Rajamanickam in collaboration with J. Bilbert and
     E. Ng.  Supported by the National Science Foundation (DMS-9504974,
     DMS-9803599, CCR-0203270), and a grant from Sandia National Lab.
     See `http://www.cise.ufl.edu/research/sparse' for ccolamd,
     csymamd, amd, colamd, symamd, and other related orderings.

     *See also:* *note symamd: doc-symamd, *note ccolamd: doc-ccolamd.

 -- Loadable Function: P = dmperm (S)
 -- Loadable Function: [P, Q, R, S] = dmperm (S)
     Perform a Dulmage-Mendelsohn permutation of the sparse matrix S.
     With a single output argument `dmperm' performs the row
     permutations P such that `S(P,:)' has no zero elements on the
     diagonal.

     Called with two or more output arguments, returns the row and
     column permutations, such that `S(P, Q)' is in block triangular
     form.  The values of R and S define the boundaries of the blocks.
     If S is square then `R == S'.

     The method used is described in: A. Pothen & C.-J. Fan. `Computing
     the Block Triangular Form of a Sparse Matrix'. ACM Trans. Math.
     Software, 16(4):303-324, 1990.

     *See also:* *note colamd: doc-colamd, *note ccolamd: doc-ccolamd.

 -- 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 one- to two-element input vector.  If S is
     n-by-n, then rows and columns with more than
     `max(16,KNOBS(1)*sqrt(n))' entries are removed prior to ordering,
     and ordered last in the output permutation P.  No rows/columns are
     removed if `KNOBS(1) < 0'.  If `KNOBS (2)' is nonzero, `stats' and
     KNOBS are printed.  The default is `KNOBS = [10 0]'.  Note that
     KNOBS differs from earlier versions of symamd.

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

     *See also:* *note colperm: doc-colperm, *note colamd: doc-colamd.

 -- Loadable Function: P = symrcm (S)
     Return the symmetric reverse Cuthill-McKee permutation of S.  P is
     a permutation vector such that `S(P, P)' tends to have its
     diagonal elements closer to the diagonal than S.  This is a good
     preordering for LU or Cholesky factorization of matrices that come
     from 'long, skinny' problems.  It works for both symmetric and
     asymmetric S.

     The algorithm represents a heuristic approach to the NP-complete
     bandwidth minimization problem.  The implementation is based in the
     descriptions found in

     E. Cuthill, J. McKee. `Reducing the Bandwidth of Sparse Symmetric
     Matrices'. Proceedings of the 24th ACM National Conference, 157-172
     1969, Brandon Press, New Jersey.

     A. George, J.W.H. Liu. `Computer Solution of Large Sparse Positive
     Definite Systems', Prentice Hall Series in Computational
     Mathematics, ISBN 0-13-165274-5, 1981.

     *See also:* *note colperm: doc-colperm, *note colamd: doc-colamd,
     *note symamd: doc-symamd.

