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

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

Copyright © 1996-2022 The Octave Project Developers

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

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

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


File: octave.info,  Node: Object Groups,  Next: Transform Groups,  Prev: Application-defined Data,  Up: Advanced Plotting

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

 -- : hggroup ()
 -- : hggroup (HAX)
 -- : hggroup (..., PROPERTY, VALUE, ...)
 -- : H = hggroup (...)
     Create handle graphics group object with axes parent HAX.

     If no parent is specified, the group is created in the current
     axes.

     Multiple property/value pairs may be specified for the hggroup, but
     they must appear in pairs.  The full list of properties is
     documented at *note Axes Properties::.

     The optional return value H is a graphics handle to the created
     hggroup object.

     Programming Note: An hggroup is a way to group base graphics
     objects such as line objects or patch objects into a single unit
     which can react appropriately.  For example, the individual lines
     of a contour plot are collected into a single hggroup so that they
     can be made visible/invisible with a single command, ‘set
     (hg_handle, "visible", "off")’.

     See also: *note addproperty: XREFaddproperty, *note addlistener:
     XREFaddlistener.

   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.

 -- : addproperty (NAME, H, TYPE)
 -- : 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 one 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", "--");

     See also: *note addlistener: XREFaddlistener, *note hggroup:
     XREFhggroup.

   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.

 -- : 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"})

     See also: *note dellistener: XREFdellistener, *note addproperty:
     XREFaddproperty, *note hggroup: XREFhggroup.

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

     See also: *note addlistener: XREFaddlistener.

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

 -- : HLINK = linkprop (H, "PROP")
 -- : HLINK = linkprop (H, {"PROP1", "PROP2", ...})
     Link graphic object properties, such that a change in one is
     propagated to the others.

     The input H is a vector of graphic handles to link.

     PROP may be a string when linking a single property, or a cell
     array of strings for multiple properties.  During the linking
     process all properties in PROP will initially be set to the values
     that exist on the first object in the list H.

     The function returns HLINK which is a special object describing the
     link.  As long as the reference HLINK exists, the link between
     graphic objects will be active.  This means that HLINK must be
     preserved in a workspace variable, a global variable, or otherwise
     stored using a function such as ‘setappdata’ or ‘guidata’.  To
     unlink properties, execute ‘clear HLINK’.

     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", "--");

     See also: *note linkaxes: XREFlinkaxes, *note addlistener:
     XREFaddlistener.

 -- : linkaxes (HAX)
 -- : linkaxes (HAX, OPTSTR)
     Link the axis limits of 2-D plots such that a change in one is
     propagated to the others.

     The axes handles to be linked are passed as the first argument HAX.

     The optional second argument is a string which defines which axis
     limits will be linked.  The possible values for OPTSTR are:

     "x"
          Link x-axes

     "y"
          Link y-axes

     "xy" (default)
          Link both axes

     "off"
          Turn off linking

     If unspecified the default is to link both X and Y axes.

     When linking, the limits from the first axes in HAX are applied to
     the other axes in the list.  Subsequent changes to any one of the
     axes will be propagated to the others.

     See also: *note linkprop: XREFlinkprop, *note addproperty:
     XREFaddproperty.

   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::
* Stair Group::
* Stem Series::
* Surface Group::


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

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

 -- : refreshdata ()
 -- : refreshdata (H)
 -- : refreshdata (H, WORKSPACE)
     Evaluate any ‘datasource’ properties of the current figure and
     update the plot if the corresponding data has changed.

     If the first argument H is a list of graphic handles, then operate
     on these objects rather than the current figure returned by ‘gcf’.

     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.6.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.6.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 properties 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.6.4 Contour Groups
.......................

Contour group objects are created by the ‘contour’, ‘contourf’, and
‘contour3’ functions.  They are also 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.6.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.6.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: Stair Group,  Prev: Line Series,  Up: Object Groups

15.4.6.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: Stair Group,  Next: Stem Series,  Prev: Quiver Group,  Up: Object Groups

15.4.6.8 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.6.9 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.6.10 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: Transform Groups,  Next: Graphics Toolkits,  Prev: Object Groups,  Up: Advanced Plotting

15.4.7 Transform Groups
-----------------------

 -- : H = hgtransform ()
 -- : H = hgtransform (PROPERTY, VALUE, ...)
 -- : H = hgtransform (HAX, ...)

     Create a graphics transform object.

     FIXME: Need to write documentation.  FIXME: Add <makehgtform> to
     seealso list when it is implemented.

     See also: *note hggroup: XREFhggroup.


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

15.4.8 Graphics Toolkits
------------------------

 -- : NAME = graphics_toolkit ()
 -- : NAME = graphics_toolkit (HLIST)
 -- : graphics_toolkit (NAME)
 -- : graphics_toolkit (HLIST, NAME)
     Query or set the default graphics toolkit which is assigned to new
     figures.

     With no inputs, return the current default graphics toolkit.  If
     the input is a list of figure graphic handles, HLIST, then return
     the name of the graphics toolkit in use for each figure.

     When called with a single input NAME set the default graphics
     toolkit to NAME.  If the toolkit is not already loaded, it is
     initialized by calling the function ‘__init_NAME__’.  If the first
     input is a list of figure handles, HLIST, then the graphics toolkit
     is set to NAME for these figures only.

     See also: *note available_graphics_toolkits:
     XREFavailable_graphics_toolkits.

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

     See also: *note graphics_toolkit: XREFgraphics_toolkit, *note
     register_graphics_toolkit: XREFregister_graphics_toolkit.

 -- : loaded_graphics_toolkits ()
     Return a cell array of the currently loaded graphics toolkits.

     See also: *note available_graphics_toolkits:
     XREFavailable_graphics_toolkits.

 -- : register_graphics_toolkit (TOOLKIT)
     List TOOLKIT as an available graphics toolkit.

     See also: *note available_graphics_toolkits:
     XREFavailable_graphics_toolkits.

* Menu:

* Customizing Toolkit Behavior::
* Hardware vs. Software Rendering::
* Precision issues::


File: octave.info,  Node: Customizing Toolkit Behavior,  Next: Hardware vs. Software Rendering,  Up: Graphics Toolkits

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

 -- : [PROG, ARGS] = gnuplot_binary ()
 -- : [OLD_PROG, OLD_ARGS] = gnuplot_binary (NEW_PROG)
 -- : [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" with no additional
     arguments.  *Note Installation::.

     See also: *note graphics_toolkit: XREFgraphics_toolkit.

   In addition, the gnuplot program usually provides a number of
different interfaces, known as terminals.  Octave normally chooses a
default terminal, but you can override this with the environment
variable ‘GNUTERM’.  This variable may be set in the shell before
starting Octave or from within Octave before plotting for the first
time.  For example:

     setenv ("GNUTERM", "wxt")
     graphics_toolkit ("gnuplot")
     plot (1:10)


File: octave.info,  Node: Hardware vs. Software Rendering,  Next: Precision issues,  Prev: Customizing Toolkit Behavior,  Up: Graphics Toolkits

15.4.8.2 Hardware vs. Software Rendering
........................................

On Windows platforms, Octave uses software rendering for the OpenGL
graphics toolkits ("qt" and "fltk") by default.  This is done to avoid
rendering and printing issues due to imperfect OpenGL driver
implementations for diverse graphic cards from different vendors.  As a
down-side, software rendering might be considerably slower than hardware
accelerated rendering.  To permanently switch back to hardware
accelerated rendering with your graphic card drivers, rename the
following file while Octave is closed:

   ‘OCTAVE-HOME\bin\opengl32.dll’
where OCTAVE-HOME is the directory in which Octave is installed (the
default is ‘C:\Octave\Octave-VERSION’).


File: octave.info,  Node: Precision issues,  Prev: Hardware vs. Software Rendering,  Up: Graphics Toolkits

15.4.8.3 Precision issues
.........................

The OpenGL graphics toolkits ("qt" and "fltk") use single precision for
rendering.  This limitation in particular applies to plots of time
series against serial dates as used by the ‘datenum’, ‘datestr’,
‘datestruct’, and ‘datetick’ functions.

   Serial dates encode timestamps as days elapsed since the year zero
with hours, minutes, seconds as the fractional part.  On December 31st
1999, the serial date representation was 730485.  A double precision
variable with this integer part allows for a resolution in its
fractional part of 1.2e-10, representing about 5 microseconds.  But with
single precision, the resolution is reduced to about 0.06, representing
45 minutes.  Any attempt to plot timestamped data with finer granularity
will result in a distorted graph.

   As a workaround, it is possible to use the "gnuplot" graphics toolkit
or subtract 2000 years—i.e., ‘datenum (2000, 0, 0)’ or 730485—from the
time values.  Due to the fact that the calendar structure repeats every
2000 years, the relation between year, month, day of month and day of
week will stay unchanged and the ticks and ticklabels produced by the
‘datetick’ function will still be correct.  Only years will lack the
millennium digit.  Thus, "2020" will be printed as "20".  For example:

     # timestamps of 24 hours in one minute steps
     t = datenum (2020, 1, 1):(1/1440):datenum (2020, 1, 2);

     # some example time series data
     x = -cos (2*pi*t) + rand (size (t)) / 10;

     subplot (1, 2, 1);
     plot (t, x);
     datetick ("x");
     xlabel ("serial date");
     title ("problem");

     subplot (1, 2, 2);
     plot (t - 730485, x);
     datetick ("x");
     xlabel ("2000 years off");
     title ("workaround");

   Similarly, other data can be translated or re-scaled to work around
this issue.


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

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

     For a matrix argument, return a row vector of logical 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 ]

     See also: *note all: XREFall.

 -- : all (X)
 -- : all (X, DIM)
     For a vector argument, return true (logical 1) if all elements of
     the vector are nonzero.

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

          all ([2, 3; 1, 0])
              ⇒ [ 1, 0 ]

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

     See also: *note any: XREFany.

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

 -- : Z = xor (X, Y)
 -- : Z = xor (X1, X2, ...)
     Return the “exclusive or” of X and Y.

     For boolean expressions X and Y, ‘xor (X, Y)’ is true if and only
     if one of X or Y is true.  Otherwise, if X and Y are both true or
     both false, ‘xor’ returns false.

     The truth table for the xor operation is

                                      X  Y    Z
                                      -  -    -
                                      0  0    0
                                      1  0    1
                                      0  1    1
                                      1  1    0

     If more than two arguments are given the xor operation is applied
     cumulatively from left to right:

          (...((x1 XOR x2) XOR x3) XOR ...)

     See also: *note and: XREFand, *note or: XREFor, *note not: XREFnot.

 -- : diff (X)
 -- : diff (X, K)
 -- : 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 the 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)’ an empty matrix is returned.

     See also: *note sort: XREFsort, *note merge: XREFmerge.

 -- : isinf (X)
     Return a logical array which is true where the elements of X are
     infinite and false where they are not.

     For example:

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

     See also: *note isfinite: XREFisfinite, *note isnan: XREFisnan,
     *note isna: XREFisna.

 -- : 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: XREFisna, *note isinf: XREFisinf, *note
     isfinite: XREFisfinite.

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

     For example:

          isfinite ([13, Inf, NA, NaN])
               ⇒ [ 1, 0, 0, 0 ]

     See also: *note isinf: XREFisinf, *note isnan: XREFisnan, *note
     isna: XREFisna.

 -- : [ERR, YI, ...] = common_size (XI, ...)
     Determine if all input arguments are either scalar or of common
     size.

     If true, 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:

          [err, a, b] = common_size ([1 2; 3 4], 5)
               ⇒ err = 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.

     See also: *note size: XREFsize, *note size_equal: XREFsize_equal,
     *note numel: XREFnumel, *note ndims: XREFndims.

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

     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 X is a multi-dimensional array of size m x n x p x ..., J
     contains the column locations as if X was flattened into a
     two-dimensional matrix of size m x (n + p + ...).

     Note that this function is particularly useful for sparse matrices,
     as it extracts the nonzero 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: XREFnonzeros.

 -- : IDX = lookup (TABLE, Y)
 -- : IDX = lookup (TABLE, Y, OPT)
     Lookup values in a *sorted* table.

     This function is usually used as a prelude to interpolation.

     If table is increasing, of length N 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 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 must be a string with letters indicating
     additional options.

     ‘m’
          Match.  ‘table(idx(i)) == y(i)’ if ‘y(i)’ occurs in table;
          otherwise, ‘idx(i)’ is zero.

     ‘b’
          Boolean.  ‘idx(i)’ is a logical 1 or 0, indicating whether
          ‘y(i)’ is contained in table or not.

     ‘l’
          Left.  For numeric lookups the leftmost subinterval shall be
          extended to minus infinity (i.e., all indices at least 1).

     ‘r’
          Right.  For numeric lookups the rightmost subinterval shall be
          extended to infinity (i.e., all indices at most N-1).

     *Note*: If TABLE is not sorted the results from ‘lookup’ will be
     unpredictable.

   If you wish to check if a variable exists at all, instead of
properties its elements may have, consult *note Status of Variables::.


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

16.2 Rearranging Matrices
=========================

 -- : fliplr (X)
     Flip array left to right.

     Return a copy of X with the order of the columns reversed.  In
     other words, X is flipped left-to-right about a vertical axis.  For
     example:

          fliplr ([1, 2; 3, 4])
               ⇒  2  1
                   4  3

     See also: *note flipud: XREFflipud, *note flip: XREFflip, *note
     rot90: XREFrot90, *note rotdim: XREFrotdim.

 -- : flipud (X)
     Flip array upside down.

     Return a copy of X with the order of the rows reversed.  In other
     words, X is flipped upside-down about a horizontal axis.  For
     example:

          flipud ([1, 2; 3, 4])
               ⇒  3  4
                   1  2

     See also: *note fliplr: XREFfliplr, *note flip: XREFflip, *note
     rot90: XREFrot90, *note rotdim: XREFrotdim.

 -- : flip (X)
 -- : flip (X, DIM)
     Return a copy of array X flipped across dimension DIM.

     If DIM is unspecified it defaults to the first non-singleton
     dimension.

     Examples:

          ## row vector
          flip ([1  2  3  4])
                ⇒  4  3  2  1

          ## column vector
          flip ([1; 2; 3; 4])
                ⇒  4
                    3
                    2
                    1

          ## 2-D matrix along dimension 1
          flip ([1 2; 3 4])
                ⇒  3  4
                    1  2

          ## 2-D matrix along dimension 2
          flip ([1 2; 3 4], 2)
                ⇒  2  1
                    4  3

     See also: *note fliplr: XREFfliplr, *note flipud: XREFflipud, *note
     rot90: XREFrot90, *note rotdim: XREFrotdim, *note permute:
     XREFpermute, *note transpose: XREFtranspose.

 -- : rot90 (A)
 -- : rot90 (A, K)
     Rotate array by 90 degree increments.

     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)

     The rotation is always performed on the plane of the first two
     dimensions, i.e., rows and columns.  To perform a rotation on any
     other plane, use ‘rotdim’.

     See also: *note rotdim: XREFrotdim, *note fliplr: XREFfliplr, *note
     flipud: XREFflipud, *note flip: XREFflip.

 -- : rotdim (X)
 -- : rotdim (X, N)
 -- : rotdim (X, N, PLANE)
     Return a copy of X with the elements rotated counterclockwise in
     90-degree increments.

     The second argument N is optional, and specifies how many 90-degree
     rotations are to be applied (the default value is 1).  Negative
     values of N rotate the matrix in a clockwise direction.

     The third argument is also optional and defines the plane of the
     rotation.  If present, PLANE is a two element vector containing two
     different valid dimensions of the matrix.  When PLANE is not given
     the first two non-singleton dimensions are used.

     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: XREFrot90, *note fliplr: XREFfliplr, *note
     flipud: XREFflipud, *note flip: XREFflip.

 -- : 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)
            ⇒ 1 1 0 0
               1 1 0 0

     Alternatively, we can concatenate A and B along the second
     dimension in 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(:,:,1,1) =

                 1 1
                 1 1

               ans(:,:,1,2) =

                 0 0
                 0 0

     See also: *note horzcat: XREFhorzcat, *note vertcat: XREFvertcat.

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

     Arrays may also be concatenated horizontally using the syntax for
     creating new matrices.  For example:

          HCAT = [ ARRAY1, ARRAY2, ... ]

     See also: *note cat: XREFcat, *note vertcat: XREFvertcat.

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

     Arrays may also be concatenated vertically using the syntax for
     creating new matrices.  For example:

          VCAT = [ ARRAY1; ARRAY2; ... ]

     See also: *note cat: XREFcat, *note horzcat: XREFhorzcat.

 -- : 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 only once).  The Nth
     dimension of A gets remapped to dimension ‘PERM(N)’.  For example:

          X = zeros ([2, 3, 5, 7]);
          size (X)
             ⇒  2   3   5   7

          size (permute (X, [2, 1, 3, 4]))
             ⇒  3   2   5   7

          size (permute (X, [1, 3, 4, 2]))
             ⇒  2   5   7   3

          ## The identity permutation
          size (permute (X, [1, 2, 3, 4]))
             ⇒  2   3   5   7

     See also: *note ipermute: XREFipermute.

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

 -- : reshape (A, M, N, ...)
 -- : reshape (A, [M N ...])
 -- : reshape (A, ..., [], ...)
 -- : reshape (A, SIZE)
     Return a matrix with the specified dimensions (M, N, ...) whose
     elements are taken from the matrix A.

     The elements of the matrix are accessed in column-major order (like
     Fortran arrays are stored).

     The following code demonstrates reshaping a 1x4 row vector into a
     2x2 square matrix.

          reshape ([1, 2, 3, 4], 2, 2)
                ⇒  1  3
                    2  4

     Note that the total number of elements in the original matrix
     (‘prod (size (A))’) must match the total number of elements in the
     new matrix (‘prod ([M N ...])’).

     A single dimension of the return matrix may be left unspecified and
     Octave will determine its size automatically.  An empty matrix ([])
     is used to flag the unspecified dimension.

     See also: *note resize: XREFresize, *note vec: XREFvec, *note
     postpad: XREFpostpad, *note cat: XREFcat, *note squeeze:
     XREFsqueeze.

 -- : resize (X, M)
 -- : resize (X, M, N, ...)
 -- : 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, N, ... are all scalars, then the
     dimensions of the result are M-by-N-by-....  If given a vector as
     input, then the dimensions of the result are given by the elements
     of that vector.

     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: XREFreshape, *note postpad: XREFpostpad,
     *note prepad: XREFprepad, *note cat: XREFcat.

 -- : Y = circshift (X, N)
 -- : Y = circshift (X, N, DIM)
     Circularly shift 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 of X
     are shifted.  If an element of N is zero, then the corresponding
     dimension of X will not be shifted.  If N is a scalar and no DIM is
     specified then the shift is applied to the first non-singular
     dimension.

     If a scalar DIM is given then operate along the specified
     dimension.  In this case N must be a scalar as well.

     Examples:

          x = [1, 2, 3;
               4, 5, 6;
               7, 8, 9];
          ## positive shift on rows (1st non-singular dim)
          circshift (x, 1)
            ⇒
                 7   8   9
                 1   2   3
                 4   5   6
          ## negative shift on rows (1st non-singular dim)
          circshift (x, -2)
            ⇒
                 7   8   9
                 1   2   3
                 4   5   6
          ## no shift of rows, shift columns by 1 (2nd dimension)
          circshift (x, [0,1])
            ⇒
                 3   1   2
                 6   4   5
                 9   7   8
          ## shift columns (2nd dimension)
          circshift (x, 1, 2)
            ⇒
                 3   1   2
                 6   4   5
                 9   7   8

     See also: *note permute: XREFpermute, *note ipermute: XREFipermute,
     *note shiftdim: XREFshiftdim.

 -- : shift (X, B)
 -- : 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.

 -- : Y = shiftdim (X, N)
 -- : [Y, NS] = shiftdim (X)
     Shift the dimensions 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: *note reshape: XREFreshape, *note permute: XREFpermute,
     *note ipermute: XREFipermute, *note circshift: XREFcircshift, *note
     squeeze: XREFsqueeze.

 -- : [S, I] = sort (X)
 -- : [S, I] = sort (X, DIM)
 -- : [S, I] = sort (X, MODE)
 -- : [S, I] = sort (X, DIM, MODE)
     Return a copy of X with the elements arranged in increasing order.

     For matrices, ‘sort’ orders the elements within columns

     For example:

          sort ([1, 2; 2, 3; 3, 1])
             ⇒  1  1
                 2  2
                 3  3

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

     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

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

     Sorting of complex entries is done first by magnitude (‘abs (Z)’)
     and for any ties by phase angle (‘angle (z)’).  For example:

          sort ([1+i; 1; 1-i])
              ⇒ 1 + 0i
                 1 - 1i
                 1 + 1i

     NaN values are treated as being greater than any other value and
     are sorted to the end of the list.

     The ‘sort’ function may also be used to sort strings and cell
     arrays of strings, in which case ASCII dictionary order (uppercase
     ’A’ precedes lowercase ’a’) of the strings is used.

     The algorithm used in ‘sort’ is optimized for the sorting of
     partially ordered lists.

     See also: *note sortrows: XREFsortrows, *note issorted:
     XREFissorted.

 -- : [S, I] = sortrows (A)
 -- : [S, I] = sortrows (A, C)
     Sort the rows of the matrix A according to the order of the columns
     specified in C.

     By default (C omitted, or a particular column unspecified in C) an
     ascending sort order is used.  However, if elements of C are
     negative then the corresponding column is sorted in descending
     order.  If the elements of A are strings then a lexicographical
     sort is used.

     Example: sort by column 2 in descending order, then 3 in ascending
     order

          x = [ 7, 1, 4;
                8, 3, 5;
                9, 3, 6 ];
          sortrows (x, [-2, 3])
             ⇒ 8  3  5
                9  3  6
                7  1  4

     See also: *note sort: XREFsort.

 -- : issorted (A)
 -- : issorted (A, MODE)
 -- : issorted (A, "rows", MODE)
     Return true if the array is sorted according to MODE, which may be
     either "ascend", "descend", or "either".

     By default, MODE is "ascend".  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: XREFsort, *note sortrows: XREFsortrows.

 -- : nth_element (X, N)
 -- : nth_element (X, N, DIM)
     Select the n-th smallest element of a vector, using the ordering
     defined by ‘sort’.

     The result is equivalent to ‘sort(X)(N)’.

     N can also be a contiguous range, either ascending ‘l:u’ or
     descending ‘u:-1:l’, in which case a range of elements is returned.

     If X is an array, ‘nth_element’ operates along the dimension
     defined by DIM, or the first non-singleton dimension if DIM is not
     given.

     Programming Note: nth_element encapsulates the C++ standard library
     algorithms nth_element and partial_sort.  On average, the
     complexity of the operation is O(M*log(K)), where
     ‘M = size (X, DIM)’ and ‘K = length (N)’.  This function is
     intended for cases where the ratio K/M is small; otherwise, it may
     be better to use ‘sort’.

     See also: *note sort: XREFsort, *note min: XREFmin, *note max:
     XREFmax.

 -- : A_LO = tril (A)
 -- : A_LO = tril (A, K)
 -- : A_LO = tril (A, K, PACK)
     Return a new matrix formed by extracting the lower triangular part
     of the matrix A, and setting all other elements to zero.

     The optional second argument specifies how many diagonals above or
     below the main diagonal should also be set to zero.  The default
     value of K is zero which includes the main diagonal as part of the
     result.  If the value of K is a nonzero integer then the selection
     of elements starts at an offset of K diagonals above the main
     diagonal for positive K or below the main diagonal for negative K.
     The absolute value of K may not be greater than the number of
     subdiagonals or superdiagonals.

     Example 1 : exclude main diagonal

          tril (ones (3), -1)
               ⇒  0  0  0
                   1  0  0
                   1  1  0


     Example 2 : include first superdiagonal

          tril (ones (3), 1)
               ⇒  1  1  0
                   1  1  1
                   1  1  1

     If the optional third argument "pack" is given then the extracted
     elements are not inserted into a matrix, but instead stacked
     column-wise one above another, and returned as a column vector.

     See also: *note triu: XREFtriu, *note istril: XREFistril, *note
     diag: XREFdiag.

 -- : A_UP = triu (A)
 -- : A_UP = triu (A, K)
 -- : A_UP = triu (A, K, PACK)
     Return a new matrix formed by extracting the upper triangular part
     of the matrix A, and setting all other elements to zero.

     The optional second argument specifies how many diagonals above or
     below the main diagonal should also be set to zero.  The default
     value of K is zero which includes the main diagonal as part of the
     result.  If the value of K is a nonzero integer then the selection
     of elements starts at an offset of K diagonals above the main
     diagonal for positive K or below the main diagonal for negative K.
     The absolute value of K may not be greater than the number of
     subdiagonals or superdiagonals.

     Example 1 : exclude main diagonal

          triu (ones (3), 1)
               ⇒  0  1  1
                   0  0  1
                   0  0  0


     Example 2 : include first subdiagonal

          triu (ones (3), -1)
               ⇒  1  1  1
                   1  1  1
                   0  1  1

     If the optional third argument "pack" is given then the extracted
     elements are not inserted into a matrix, but instead stacked
     column-wise one above another, and returned as a column vector.

     See also: *note tril: XREFtril, *note istriu: XREFistriu, *note
     diag: XREFdiag.

 -- : V = vec (X)
 -- : 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)’.

     See also: *note vech: XREFvech, *note resize: XREFresize, *note
     cat: XREFcat.

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

     This has uses in matrix calculus where the underlying matrix is
     symmetric and it would be pointless to keep values above the main
     diagonal.

     See also: *note vec: XREFvec.

 -- : prepad (X, L)
 -- : prepad (X, L, C)
 -- : prepad (X, L, C, DIM)
     Prepend the scalar value C to the vector X until it is of length L.
     If C is not given, 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.

     If DIM is larger than the dimensions of X, the result will have DIM
     dimensions.

     See also: *note postpad: XREFpostpad, *note cat: XREFcat, *note
     resize: XREFresize.

 -- : postpad (X, L)
 -- : postpad (X, L, C)
 -- : postpad (X, L, C, DIM)
     Append the scalar value C to the vector X until it is of length L.
     If C is not given, 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.

     If DIM is larger than the dimensions of X, the result will have DIM
     dimensions.

     See also: *note prepad: XREFprepad, *note cat: XREFcat, *note
     resize: XREFresize.

 -- : M = diag (V)
 -- : M = diag (V, K)
 -- : M = diag (V, M, N)
 -- : V = diag (M)
 -- : V = diag (M, 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 superdiagonal.  If it is negative, it is placed
     on the -K-th subdiagonal.  The default value of K is 0, and the
     vector is placed on the main diagonal.  For example:

          diag ([1, 2, 3], 1)
             ⇒  0  1  0  0
                 0  0  2  0
                 0  0  0  3
                 0  0  0  0

     The 3-input form returns a diagonal matrix with vector V on the
     main diagonal and the resulting matrix being of size M rows x N
     columns.

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

 -- : blkdiag (A, B, C, ...)
     Build a block diagonal matrix from A, B, C, ...

     All arguments must be numeric and either two-dimensional matrices
     or scalars.  If any argument is of type sparse, the output will
     also be sparse.

     See also: *note diag: XREFdiag, *note horzcat: XREFhorzcat, *note
     vertcat: XREFvertcat, *note sparse: XREFsparse.


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

16.3 Special Utility Matrices
=============================

 -- : eye (N)
 -- : eye (M, N)
 -- : eye ([M N])
 -- : eye (..., CLASS)
     Return an identity matrix.

     If invoked with a single scalar argument N, return a square NxN
     identity matrix.

     If supplied two scalar arguments (M, N), ‘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.  Any negative dimensions are treated as zero.  These
     odd definitions are for compatibility with MATLAB.

     See also: *note speye: XREFspeye, *note ones: XREFones, *note
     zeros: XREFzeros.

 -- : VAL = ones (N)
 -- : VAL = ones (M, N)
 -- : VAL = ones (M, N, K, ...)
 -- : VAL = ones ([M N ...])
 -- : VAL = ones (..., "LIKE", VAR))
 -- : VAL = ones (..., CLASS)
     Return a matrix or N-dimensional array whose elements are all 1.

     If invoked with a single scalar integer argument N, return a square
     NxN matrix.

     If invoked with two or more scalar integer arguments, or a vector
     of integer values, return an array with the given dimensions.

     To create a constant matrix whose values are all the same use an
     expression such as

          val_matrix = val * ones (m, n)

     If a variable VAR is specified after "like", the output VAL will
     have the same data type, complexity, and sparsity as VAR.

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

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

     See also: *note zeros: XREFzeros.

 -- : VAL = zeros (N)
 -- : VAL = zeros (M, N)
 -- : VAL = zeros (M, N, K, ...)
 -- : VAL = zeros ([M N ...])
 -- : VAL = zeros (..., "LIKE", VAR))
 -- : VAL = 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
     NxN matrix.

     If invoked with two or more scalar integer arguments, or a vector
     of integer values, return an array with the given dimensions.

     If a variable VAR is specified after "like", the output VAL will
     have the same data type, complexity, and sparsity as VAR.

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

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

     See also: *note ones: XREFones.

 -- : repmat (A, M)
 -- : repmat (A, M, N)
 -- : repmat (A, M, N, P ...)
 -- : repmat (A, [M N])
 -- : repmat (A, [M N P ...])
     Repeat matrix or N-D array.

     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.  For copying
     along more than two dimensions, specify the number of times to copy
     across each dimension M, N, P, ..., in a vector in the second
     argument.

     See also: *note bsxfun: XREFbsxfun, *note kron: XREFkron, *note
     repelems: XREFrepelems.

 -- : 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: XREFrepmat, *note cat: XREFcat.

 -- : XXX = repelem (X, R)
 -- : XXX = repelem (X, R_1, ..., R_N)
     Construct an array of repeated elements from X and repeat
     instructions R_1, ....

     X must be a scalar, vector, or N-dimensional array.

     A repeat instruction R_J must either be a scalar or a vector.  If
     the instruction is a scalar then each component of X in dimension J
     is repeated R_J times.  If the instruction is a vector then it must
     have the same number of elements as the corresponding dimension J
     of X.  In this case, the Kth component of dimension J is repeated
     ‘R_J(K)’ times.

     If X is a scalar or vector then ‘repelem’ may be called with just a
     single repeat instruction R and ‘repelem’ will return a vector with
     the same orientation as the input.

     If X is a matrix then at least two R_Js must be specified.

     Note: Using ‘repelem’ with a vector X and a vector for R_J is
     equivalent to Run Length Decoding.

     Examples:

          A = [1 2 3 4 5];
          B = [2 1 0 1 2];
          repelem (A, B)
            ⇒   1   1   2   4   5   5

          A = magic (3)
            ⇒ A =
                 8   1   6
                 3   5   7
                 4   9   2
          B1 = [1 2 3];
          B2 = 2;
          repelem (A, B1, B2)
            ⇒     8   8   1   1   6   6
                   3   3   5   5   7   7
                   3   3   5   5   7   7
                   4   4   9   9   2   2
                   4   4   9   9   2   2
                   4   4   9   9   2   2

     More R_J may be specified than the number of dimensions of X.  Any
     excess R_J must be scalars (because X’s size in those dimensions is
     only 1), and X will be replicated in those dimensions accordingly.

          A = [1 2 3 4 5];
          B1 = 2;
          B2 = [2 1 3 0 2];
          B3 = 3;
          repelem (A, B1, B2, B3)
            ⇒    ans(:,:,1) =
                     1   1   2   3   3   3   5   5
                     1   1   2   3   3   3   5   5

                  ans(:,:,2) =

                     1   1   2   3   3   3   5   5
                     1   1   2   3   3   3   5   5

                  ans(:,:,3) =
                     1   1   2   3   3   3   5   5
                     1   1   2   3   3   3   5   5

     R_J must be specified in order.  A placeholder of 1 may be used for
     dimensions which do not need replication.

          repelem ([-1, 0; 0, 1], 1, 2, 1, 2)
            ⇒  ans(:,:,1,1) =
                  -1  -1   0   0
                   0   0   1   1

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

     If fewer R_J are given than the number of dimensions in X,
     ‘repelem’ will assume R_J is 1 for those dimensions.

          A = cat (3, [-1 0; 0 1], [-1 0; 0 1])
            ⇒  ans(:,:,1) =
                  -1   0
                   0   1

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

          repelem (A,2,3)
            ⇒  ans(:,:,1) =
                  -1  -1  -1   0   0   0
                  -1  -1  -1   0   0   0
                   0   0   0   1   1   1
                   0   0   0   1   1   1

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

     ‘repelem’ preserves the class of X, and works with strings, cell
     arrays, NA, and NAN inputs.  If any R_J is 0 the output will be an
     empty array.

          repelem ("Octave", 2, 3)
            ⇒    OOOccctttaaavvveee
                  OOOccctttaaavvveee

          repelem ([1 2 3; 1 2 3], 2, 0)
            ⇒    [](4x0)

     See also: *note cat: XREFcat, *note kron: XREFkron, *note repmat:
     XREFrepmat.

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

 -- : linspace (START, END)
 -- : linspace (START, END, N)
     Return a row vector with N linearly spaced elements between START
     and END.

     If the number of elements is greater than one, then the endpoints
     START and END are always included in the range.  If START is
     greater than END, the elements are stored in decreasing order.  If
     the number of points is not specified, a value of 100 is used.

     The ‘linspace’ function returns a row vector when both START and
     END are scalars.  If one, or both, inputs are vectors, then
     ‘linspace’ transforms them to column vectors and returns a matrix
     where each row is an independent sequence between
     ‘START(ROW_N), END(ROW_N)’.

     For compatibility with MATLAB, return the second argument (END)
     when only a single value (N = 1) is requested.

     See also: *note colon: XREFcolon, *note logspace: XREFlogspace.

 -- : logspace (A, B)
 -- : logspace (A, B, N)
 -- : logspace (A, pi, N)
     Return a row vector with N elements logarithmically spaced from
     10^A to 10^B.

     If N is unspecified it defaults to 50.

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

     Also for compatibility with MATLAB, return the right-hand side of
     the range (10^B) when just a single value is requested.

     See also: *note linspace: XREFlinspace.

 -- : rand (N)
 -- : rand (M, N, ...)
 -- : rand ([M N ...])
 -- : V = rand ("state")
 -- : rand ("state", V)
 -- : rand ("state", "reset")
 -- : V = rand ("seed")
 -- : rand ("seed", V)
 -- : rand ("seed", "reset")
 -- : rand (..., "single")
 -- : rand (..., "double")
     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 by contributing entropy
     from the wall clock time, the CPU time, the current fraction of a
     second, the process ID and—if available—up to 1024 bits from the
     C++ random numbers source ‘random_device’, which might be
     non-deterministic (implementation specific).  Note that this
     differs from MATLAB, which always initializes the state to the same
     state at startup.  To obtain behavior comparable to MATLAB,
     initialize with a deterministic state vector in Octave’s startup
     files (*note Startup Files::).

     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 produced
     by the old generators.  To do this the keyword "seed" is used to
     specify that the old generators should be used, 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.

     The class of the value returned can be controlled by a trailing
     "double" or "single" argument.  These are the only valid classes.

     See also: *note randn: XREFrandn, *note rande: XREFrande, *note
     randg: XREFrandg, *note randp: XREFrandp.

 -- : randi (IMAX)
 -- : randi (IMAX, N)
 -- : randi (IMAX, M, N, ...)
 -- : randi ([IMIN IMAX], ...)
 -- : 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
     ‘flintmax’ function.  For IEEE floating point numbers this value is
     2^{53} - 1.

     See also: *note rand: XREFrand.

 -- : randn (N)
 -- : randn (M, N, ...)
 -- : randn ([M N ...])
 -- : V = randn ("state")
 -- : randn ("state", V)
 -- : randn ("state", "reset")
 -- : V = randn ("seed")
 -- : randn ("seed", V)
 -- : randn ("seed", "reset")
 -- : randn (..., "single")
 -- : randn (..., "double")
     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.

     The class of the value returned can be controlled by a trailing
     "double" or "single" argument.  These are the only valid classes.

     Reference: G. Marsaglia and W.W. Tsang, ‘Ziggurat Method for
     Generating Random Variables’, J. Statistical Software, vol 5, 2000,
     <https://www.jstatsoft.org/v05/i08/>

     See also: *note rand: XREFrand, *note rande: XREFrande, *note
     randg: XREFrandg, *note randp: XREFrandp.

 -- : rande (N)
 -- : rande (M, N, ...)
 -- : rande ([M N ...])
 -- : V = rande ("state")
 -- : rande ("state", V)
 -- : rande ("state", "reset")
 -- : V = rande ("seed")
 -- : rande ("seed", V)
 -- : rande ("seed", "reset")
 -- : rande (..., "single")
 -- : rande (..., "double")
     Return a matrix with exponentially distributed random elements.

     The arguments are handled the same as the arguments for ‘rand’.

     By default, ‘rande’ uses the Marsaglia and Tsang “Ziggurat
     technique” to transform from a uniform to an exponential
     distribution.

     The class of the value returned can be controlled by a trailing
     "double" or "single" argument.  These are the only valid classes.

     Reference: G. Marsaglia and W.W. Tsang, ‘Ziggurat Method for
     Generating Random Variables’, J. Statistical Software, vol 5, 2000,
     <https://www.jstatsoft.org/v05/i08/>

     See also: *note rand: XREFrand, *note randn: XREFrandn, *note
     randg: XREFrandg, *note randp: XREFrandp.

 -- : randp (L, N)
 -- : randp (L, M, N, ...)
 -- : randp (L, [M N ...])
 -- : V = randp ("state")
 -- : randp ("state", V)
 -- : randp ("state", "reset")
 -- : V = randp ("seed")
 -- : randp ("seed", V)
 -- : randp ("seed", "reset")
 -- : randp (..., "single")
 -- : randp (..., "double")
     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.

     The class of the value returned can be controlled by a trailing
     "double" or "single" argument.  These are the only valid classes.

     See also: *note rand: XREFrand, *note randn: XREFrandn, *note
     rande: XREFrande, *note randg: XREFrandg.

 -- : randg (A, N)
 -- : randg (A, M, N, ...)
 -- : randg (A, [M N ...])
 -- : V = randg ("state")
 -- : randg ("state", V)
 -- : randg ("state", "reset")
 -- : V = randg ("seed")
 -- : randg ("seed", V)
 -- : randg ("seed", "reset")
 -- : randg (..., "single")
 -- : randg (..., "double")

     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)

     The class of the value returned can be controlled by a trailing
     "double" or "single" argument.  These are the only valid classes.

     See also: *note rand: XREFrand, *note randn: XREFrandn, *note
     rande: XREFrande, *note randp: XREFrandp.

 -- : rng (SEED)
 -- : rng (SEED, "GENERATOR")
 -- : rng ("shuffle")
 -- : rng ("shuffle", "GENERATOR")
 -- : rng ("default")
 -- : S = rng ()
 -- : rng (S)
 -- : S = rng (...)
     Set or query the seed of the random number generator used by ‘rand’
     and ‘randn’.

     The input SEED is a scalar numeric value used to initialize the
     state vector of the random number generator.

     The optional string GENERATOR specifies the type of random number
     generator to be used.  Its value can be "twister", "v5uniform", or
     "v5normal".  The "twister" keyword is described below.  "v5uniform"
     and "v5normal" refer to older versions of Octave that used to use a
     different random number generator.

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

     The random number generator can be reset to default values using
     the "default" keyword.  The default values are to use the Mersenne
     Twister generator with a seed of 0.

     The optional return value S contains the state of the random number
     generator at the time the function is called (i.e., before it might
     be modified according to the input arguments).  It is encoded as a
     structure variable with three fields: "Type", "Seed", and "State".
     The random number generator can be restored to the state S using
     ‘rng (S)’.  This is useful when the identical sequence of
     pseudo-random numbers is required for an algorithm.

     By default, and with the "twister" option, pseudo-random sequences
     are computed using 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.

     See also: *note rand: XREFrand, *note randn: XREFrandn.

   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.

 -- : randperm (N)
 -- : randperm (N, M)
     Return a row vector containing a random permutation of ‘1:N’.

     If M is supplied, return M unique entries, sampled without
     replacement from ‘1:N’.

     The complexity is O(N) in memory and O(M) in time, unless M < N/5,
     in which case O(M) memory is used as well.  The randomization is
     performed using rand().  All permutations are equally likely.

     See also: *note perms: XREFperms.

   ---------- 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.4 Famous Matrices
====================

The following functions return famous matrix forms.

 -- : gallery (NAME)
 -- : gallery (NAME, ARGS)
     Create interesting matrices for testing.

 -- : C = gallery ("cauchy", X)
 -- : C = gallery ("cauchy", X, Y)
     Create a Cauchy matrix.

 -- : C = gallery ("chebspec", N)
 -- : C = gallery ("chebspec", N, K)
     Create a Chebyshev spectral differentiation matrix.

 -- : C = gallery ("chebvand", P)
 -- : C = gallery ("chebvand", M, P)
     Create a Vandermonde-like matrix for the Chebyshev polynomials.

 -- : A = gallery ("chow", N)
 -- : A = gallery ("chow", N, ALPHA)
 -- : A = gallery ("chow", N, ALPHA, DELTA)
     Create a Chow matrix – a singular Toeplitz lower Hessenberg matrix.

 -- : C = gallery ("circul", V)
     Create a circulant matrix.

 -- : A = gallery ("clement", N)
 -- : A = gallery ("clement", N, K)
     Create a tridiagonal matrix with zero diagonal entries.

 -- : C = gallery ("compar", A)
 -- : C = gallery ("compar", A, K)
     Create a comparison matrix.

 -- : A = gallery ("condex", N)
 -- : A = gallery ("condex", N, K)
 -- : A = gallery ("condex", N, K, THETA)
     Create a "counterexample" matrix to a condition estimator.

 -- : A = gallery ("cycol", [M N])
 -- : A = gallery ("cycol", N)
 -- : A = gallery (..., K)
     Create a matrix whose columns repeat cyclically.

 -- : [C, D, E] = gallery ("dorr", N)
 -- : [C, D, E] = gallery ("dorr", N, THETA)
 -- : A = gallery ("dorr", ...)
     Create a diagonally dominant, ill-conditioned, tridiagonal matrix.

 -- : A = gallery ("dramadah", N)
 -- : A = gallery ("dramadah", N, K)
     Create a (0, 1) matrix whose inverse has large integer entries.

 -- : A = gallery ("fiedler", C)
     Create a symmetric Fiedler matrix.

 -- : A = gallery ("forsythe", N)
 -- : A = gallery ("forsythe", N, ALPHA)
 -- : A = gallery ("forsythe", N, ALPHA, LAMBDA)
     Create a Forsythe matrix (a perturbed Jordan block).

 -- : F = gallery ("frank", N)
 -- : F = gallery ("frank", N, K)
     Create a Frank matrix (ill-conditioned eigenvalues).

 -- : C = gallery ("gcdmat", N)
     Create a greatest common divisor matrix.

     C is an N-by-N matrix whose values correspond to the greatest
     common divisor of its coordinate values, i.e., C(i,j) correspond
     ‘gcd (i, j)’.

 -- : A = gallery ("gearmat", N)
 -- : A = gallery ("gearmat", N, I)
 -- : A = gallery ("gearmat", N, I, J)
     Create a Gear matrix.

 -- : G = gallery ("grcar", N)
 -- : G = gallery ("grcar", N, K)
     Create a Toeplitz matrix with sensitive eigenvalues.

 -- : A = gallery ("hanowa", N)
 -- : A = gallery ("hanowa", N, D)
     Create a matrix whose eigenvalues lie on a vertical line in the
     complex plane.

 -- : V = gallery ("house", X)
 -- : [V, BETA] = gallery ("house", X)
     Create a householder matrix.

 -- : A = gallery ("integerdata", IMAX, [M N ...], J)
 -- : A = gallery ("integerdata", IMAX, M, N, ..., J)
 -- : A = gallery ("integerdata", [IMIN, IMAX], [M N ...], J)
 -- : A = gallery ("integerdata", [IMIN, IMAX], M, N, ..., J)
 -- : A = gallery ("integerdata", ..., "CLASS")
     Create a matrix with random integers in the range [1, IMAX].  If
     IMIN is given then the integers are in the range [IMIN, IMAX].

     The second input is a matrix of dimensions describing the size of
     the output.  The dimensions can also be input as comma-separated
     arguments.

     The input J is an integer index in the range [0, 2^32-1].  The
     values of the output matrix are always exactly the same
     (reproducibility) for a given size input and J index.

     The final optional argument determines the class of the resulting
     matrix.  Possible values for CLASS: "uint8", "uint16", "uint32",
     "int8", "int16", int32", "single", "double".  The default is
     "double".

 -- : A = gallery ("invhess", X)
 -- : A = gallery ("invhess", X, Y)
     Create the inverse of an upper Hessenberg matrix.

 -- : A = gallery ("invol", N)
     Create an involutory matrix.

 -- : A = gallery ("ipjfact", N)
 -- : A = gallery ("ipjfact", N, K)
     Create a Hankel matrix with factorial elements.

 -- : A = gallery ("jordbloc", N)
 -- : A = gallery ("jordbloc", N, LAMBDA)
     Create a Jordan block.

 -- : U = gallery ("kahan", N)
 -- : U = gallery ("kahan", N, THETA)
 -- : U = gallery ("kahan", N, THETA, PERT)
     Create a Kahan matrix (upper trapezoidal).

 -- : A = gallery ("kms", N)
 -- : A = gallery ("kms", N, RHO)
     Create a Kac-Murdock-Szego Toeplitz matrix.

 -- : B = gallery ("krylov", A)
 -- : B = gallery ("krylov", A, X)
 -- : B = gallery ("krylov", A, X, J)
     Create a Krylov matrix.

 -- : A = gallery ("lauchli", N)
 -- : A = gallery ("lauchli", N, MU)
     Create a Lauchli matrix (rectangular).

 -- : A = gallery ("lehmer", N)
     Create a Lehmer matrix (symmetric positive definite).

 -- : T = gallery ("lesp", N)
     Create a tridiagonal matrix with real, sensitive eigenvalues.

 -- : A = gallery ("lotkin", N)
     Create a Lotkin matrix.

 -- : A = gallery ("minij", N)
     Create a symmetric positive definite matrix MIN(i,j).

 -- : A = gallery ("moler", N)
 -- : A = gallery ("moler", N, ALPHA)
     Create a Moler matrix (symmetric positive definite).

 -- : [A, T] = gallery ("neumann", N)
     Create a singular matrix from the discrete Neumann problem
     (sparse).

 -- : A = gallery ("normaldata", [M N ...], J)
 -- : A = gallery ("normaldata", M, N, ..., J)
 -- : A = gallery ("normaldata", ..., "CLASS")
     Create a matrix with random samples from the standard normal
     distribution (mean = 0, std = 1).

     The first input is a matrix of dimensions describing the size of
     the output.  The dimensions can also be input as comma-separated
     arguments.

     The input J is an integer index in the range [0, 2^32-1].  The
     values of the output matrix are always exactly the same
     (reproducibility) for a given size input and J index.

     The final optional argument determines the class of the resulting
     matrix.  Possible values for CLASS: "single", "double".  The
     default is "double".

 -- : Q = gallery ("orthog", N)
 -- : Q = gallery ("orthog", N, K)
     Create orthogonal and nearly orthogonal matrices.

 -- : A = gallery ("parter", N)
     Create a Parter matrix (a Toeplitz matrix with singular values near
     pi).

 -- : P = gallery ("pei", N)
 -- : P = gallery ("pei", N, ALPHA)
     Create a Pei matrix.

 -- : A = gallery ("poisson", N)
     Create a block tridiagonal matrix from Poisson’s equation (sparse).

 -- : A = gallery ("prolate", N)
 -- : A = gallery ("prolate", N, W)
     Create a prolate matrix (symmetric, ill-conditioned Toeplitz
     matrix).

 -- : H = gallery ("randhess", X)
     Create a random, orthogonal upper Hessenberg matrix.

 -- : A = gallery ("rando", N)
 -- : A = gallery ("rando", N, K)
     Create a random matrix with elements -1, 0 or 1.

 -- : A = gallery ("randsvd", N)
 -- : A = gallery ("randsvd", N, KAPPA)
 -- : A = gallery ("randsvd", N, KAPPA, MODE)
 -- : A = gallery ("randsvd", N, KAPPA, MODE, KL)
 -- : A = gallery ("randsvd", N, KAPPA, MODE, KL, KU)
     Create a random matrix with pre-assigned singular values.

 -- : A = gallery ("redheff", N)
     Create a zero and ones matrix of Redheffer associated with the
     Riemann hypothesis.

 -- : A = gallery ("riemann", N)
     Create a matrix associated with the Riemann hypothesis.

 -- : A = gallery ("ris", N)
     Create a symmetric Hankel matrix.

 -- : A = gallery ("smoke", N)
 -- : A = gallery ("smoke", N, K)
     Create a complex matrix, with a "smoke ring" pseudospectrum.

 -- : T = gallery ("toeppd", N)
 -- : T = gallery ("toeppd", N, M)
 -- : T = gallery ("toeppd", N, M, W)
 -- : T = gallery ("toeppd", N, M, W, THETA)
     Create a symmetric positive definite Toeplitz matrix.

 -- : P = gallery ("toeppen", N)
 -- : P = gallery ("toeppen", N, A)
 -- : P = gallery ("toeppen", N, A, B)
 -- : P = gallery ("toeppen", N, A, B, C)
 -- : P = gallery ("toeppen", N, A, B, C, D)
 -- : P = gallery ("toeppen", N, A, B, C, D, E)
     Create a pentadiagonal Toeplitz matrix (sparse).

 -- : A = gallery ("tridiag", X, Y, Z)
 -- : A = gallery ("tridiag", N)
 -- : A = gallery ("tridiag", N, C, D, E)
     Create a tridiagonal matrix (sparse).

 -- : T = gallery ("triw", N)
 -- : T = gallery ("triw", N, ALPHA)
 -- : T = gallery ("triw", N, ALPHA, K)
     Create an upper triangular matrix discussed by Kahan, Golub, and
     Wilkinson.

 -- : A = gallery ("uniformdata", [M N ...], J)
 -- : A = gallery ("uniformdata", M, N, ..., J)
 -- : A = gallery ("uniformdata", ..., "CLASS")
     Create a matrix with random samples from the standard uniform
     distribution (range [0,1]).

     The first input is a matrix of dimensions describing the size of
     the output.  The dimensions can also be input as comma-separated
     arguments.

     The input J is an integer index in the range [0, 2^32-1].  The
     values of the output matrix are always exactly the same
     (reproducibility) for a given size input and J index.

     The final optional argument determines the class of the resulting
     matrix.  Possible values for CLASS: "single", "double".  The
     default is "double".

 -- : A = gallery ("wathen", NX, NY)
 -- : A = gallery ("wathen", NX, NY, K)
     Create the Wathen matrix.

 -- : [A, B] = gallery ("wilk", N)
     Create various specific matrices devised/discussed by Wilkinson.

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

        • Multiplying any row or column by -1 and the matrix will remain
          a Hadamard matrix.

     See also: *note compan: XREFcompan, *note hankel: XREFhankel, *note
     toeplitz: XREFtoeplitz.

 -- : hankel (C)
 -- : hankel (C, R)
     Return the Hankel matrix constructed from 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 hadamard: XREFhadamard, *note toeplitz:
     XREFtoeplitz.

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

     Hilbert matrices are close to being singular which make them
     difficult to invert with numerical routines.  Comparing the
     condition number of a random matrix 5x5 matrix with that of a
     Hilbert matrix of order 5 reveals just how difficult the problem
     is.

          cond (rand (5))
             ⇒ 14.392
          cond (hilb (5))
             ⇒ 4.7661e+05

     See also: *note invhilb: XREFinvhilb.

 -- : 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 ‘inv (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: XREFhilb.

 -- : magic (N)

     Create an N-by-N magic square.

     A magic square is an arrangement of the integers ‘1:n^2’ such that
     the row sums, column sums, and diagonal sums are all equal to the
     same value.

     Note: N must be a scalar greater than or equal to 3.  If you supply
     N less than 3, magic returns either a nonmagic square, or else the
     degenerate magic squares 1 and [].

 -- : pascal (N)
 -- : pascal (N, T)
     Return the Pascal matrix of order N if ‘T = 0’.

     The default value of T is 0.

     When ‘T = 1’, return the pseudo-lower triangular Cholesky factor of
     the Pascal matrix (The sign of some columns may be negative).  This
     matrix is its own inverse, that is ‘pascal (N, 1) ^ 2 == eye (N)’.

     If ‘T = -1’, return the true Cholesky factor with strictly positive
     values on the diagonal.

     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 chol: XREFchol.

 -- : rosser ()
     Return the Rosser matrix.

     This is a difficult test case used to evaluate eigenvalue
     algorithms.

     See also: *note wilkinson: XREFwilkinson, *note eig: XREFeig.

 -- : toeplitz (C)
 -- : toeplitz (C, R)
     Return the Toeplitz matrix constructed from the first column C, and
     optionally the first row R.

     If the second argument is omitted, the first row is taken to be the
     same as the first column.  If the first element of R is not the
     same as the first element of C, the first element of C is used.

     A Toeplitz, or diagonal-constant, matrix has the same value along
     each diagonal.  Although it need not be square, it often is.  An
     MxN Toeplitz matrix has the form:

          c(1)  r(2)   r(3)  ...  r(n)
          c(2)  c(1)   r(2)  ... r(n-1)
          c(3)  c(2)   c(1)  ... r(n-2)
           .     .      .   .      .
           .     .      .     .    .
           .     .      .       .  .
          c(m) c(m-1) c(m-2) ... c(m-n+1)

     See also: *note hankel: XREFhankel.

 -- : vander (C)
 -- : 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 polyfit: XREFpolyfit.

 -- : wilkinson (N)
     Return the Wilkinson matrix of order N.

     Wilkinson matrices are symmetric and tridiagonal with pairs of
     nearly, but not exactly, equal eigenvalues.  They are useful in
     testing the behavior and performance of eigenvalue solvers.

     See also: *note rosser: XREFrosser, *note eig: XREFeig.


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

 -- : exp (X)
     Compute ‘e^x’ for each element of X.

     To compute the matrix exponential, *note Linear Algebra::.

     See also: *note log: XREFlog.

 -- : expm1 (X)
     Compute ‘exp (X) - 1’ accurately in the neighborhood of zero.

     See also: *note exp: XREFexp.

 -- : log (X)
     Compute the natural logarithm, ‘ln (X)’, for each element of X.

     To compute the matrix logarithm, *note Linear Algebra::.

     See also: *note exp: XREFexp, *note log1p: XREFlog1p, *note log2:
     XREFlog2, *note log10: XREFlog10, *note logspace: XREFlogspace.

 -- : reallog (X)
     Return the real-valued natural logarithm of each element of X.

     If any element results in a complex return value ‘reallog’ aborts
     and issues an error.

     See also: *note log: XREFlog, *note realpow: XREFrealpow, *note
     realsqrt: XREFrealsqrt.

 -- : log1p (X)
     Compute ‘log (1 + X)’ accurately in the neighborhood of zero.

     See also: *note log: XREFlog, *note exp: XREFexp, *note expm1:
     XREFexpm1.

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

     See also: *note log: XREFlog, *note log2: XREFlog2, *note logspace:
     XREFlogspace, *note exp: XREFexp.

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

     If called with one output, compute the base-2 logarithm such that
     ‘2^Y = X’.

     If called with two output arguments, split X into binary mantissa
     (F) and exponent (E) such that ‘X = F * 2^E’ where
     ‘1/2 <= abs (F) < 1’ and E is an integer.  If ‘x = 0’, ‘f = e = 0’.

     See also: *note pow2: XREFpow2, *note log: XREFlog, *note log10:
     XREFlog10, *note exp: XREFexp.

 -- : pow2 (X)
 -- : pow2 (F, E)
     With one input argument, compute 2 .^ x for each element of X.

     With two input arguments, return f .* (2 .^ e).

     See also: *note log2: XREFlog2, *note nextpow2: XREFnextpow2, *note
     power: XREFpower.

 -- : N = nextpow2 (X)
     Compute the exponent for the smallest power of two larger than the
     input.

     For each element in the input array X, return the first integer N
     such that 2^n ≥ abs (x).

     See also: *note pow2: XREFpow2, *note log2: XREFlog2.

 -- : 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 power: XREFpower, *note reallog: XREFreallog, *note
     realsqrt: XREFrealsqrt.

 -- : 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, *note Linear Algebra::.

     See also: *note realsqrt: XREFrealsqrt, *note nthroot: XREFnthroot.

 -- : realsqrt (X)
     Return the real-valued square root of each element of X.

     If any element results in a complex return value ‘realsqrt’ aborts
     and issues an error.

     See also: *note sqrt: XREFsqrt, *note realpow: XREFrealpow, *note
     reallog: XREFreallog.

 -- : cbrt (X)
     Compute the real-valued cube root of each element of X.

     Unlike ‘X^(1/3)’, the result will be negative if X is negative.

     If any element of X is complex, ‘cbrt’ aborts with an error.

     See also: *note nthroot: XREFnthroot.

 -- : nthroot (X, N)

     Compute the real (non-complex) N-th root of X.

     X must have all real entries and N must be a scalar.  If N is an
     even integer and X has negative entries then ‘nthroot’ aborts and
     issues an error.

     Example:

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

     See also: *note realsqrt: XREFrealsqrt, *note sqrt: XREFsqrt, *note
     cbrt: XREFcbrt.


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

 -- : abs (Z)
     Compute the magnitude of Z.

     The magnitude is defined as |Z| = ‘sqrt (x^2 + y^2)’.

     For example:

          abs (3 + 4i)
               ⇒ 5

     See also: *note arg: XREFarg.

 -- : arg (Z)
 -- : angle (Z)
     Compute the argument, i.e., angle of Z.

     This is defined as, THETA = ‘atan2 (Y, X)’, in radians.

     For example:

          arg (3 + 4i)
               ⇒ 0.92730

     See also: *note abs: XREFabs.

 -- : conj (Z)
     Return the complex conjugate of Z.

     The complex conjugate is defined as ‘conj (Z)’ = X - IY.

     See also: *note real: XREFreal, *note imag: XREFimag.

 -- : cplxpair (Z)
 -- : cplxpair (Z, TOL)
 -- : cplxpair (Z, TOL, DIM)
     Sort the numbers Z into complex conjugate pairs ordered by
     increasing real part.

     The negative imaginary complex numbers are placed first within each
     pair.  All real numbers (those with ‘abs (imag (Z)) / abs (Z) <
     TOL’) are placed after the complex pairs.

     TOL is a weighting factor in the range [0, 1) which determines the
     tolerance of the matching.  The default value is ‘100 * eps’ and
     the resulting tolerance for a given complex pair is ‘TOL * abs
     (Z(i)))’.

     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)

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

     See also: *note real: XREFreal, *note conj: XREFconj.

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

     See also: *note imag: XREFimag, *note conj: XREFconj.


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’ or use the ‘deg2rad’ function.  For example, ‘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.  As an example, ‘sin’ expects
an angle in radians while ‘sind’ expects an angle in degrees.

   Octave uses the C library trigonometric functions.  It is expected
that these functions are defined by the ISO/IEC 9899 Standard.  This
Standard is available at:
<http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1124.pdf>.  Section
F.9.1 deals with the trigonometric functions.  The behavior of most of
the functions is relatively straightforward.  However, there are some
exceptions to the standard behavior.  Many of the exceptions involve the
behavior for -0.  The most complex case is atan2.  Octave exactly
implements the behavior given in the Standard.  Including ‘atan2(+- 0,
0)’ returns ‘+- pi’.

   It should be noted that MATLAB uses different definitions which
apparently do not distinguish -0.

 -- : RAD = deg2rad (DEG)

     Convert degrees to radians.

     The input DEG must be a scalar, vector, or N-dimensional array of
     double or single floating point values.  DEG may be complex in
     which case the real and imaginary components are converted
     separately.

     The output RAD is the same size and shape as DEG with degrees
     converted to radians using the conversion constant ‘pi/180’.

     Example:

          deg2rad ([0, 90, 180, 270, 360])
            ⇒  0.00000   1.57080   3.14159   4.71239   6.28319

     See also: *note rad2deg: XREFrad2deg.

 -- : DEG = rad2deg (RAD)

     Convert radians to degrees.

     The input RAD must be a scalar, vector, or N-dimensional array of
     double or single floating point values.  RAD may be complex in
     which case the real and imaginary components are converted
     separately.

     The output DEG is the same size and shape as RAD with radians
     converted to degrees using the conversion constant ‘180/pi’.

     Example:

          rad2deg ([0, pi/2, pi, 3/2*pi, 2*pi])
            ⇒  0    90   180   270   360

     See also: *note deg2rad: XREFdeg2rad.

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

     See also: *note asin: XREFasin, *note sind: XREFsind, *note sinh:
     XREFsinh.

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

     See also: *note acos: XREFacos, *note cosd: XREFcosd, *note cosh:
     XREFcosh.

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

     See also: *note atan: XREFatan, *note tand: XREFtand, *note tanh:
     XREFtanh.

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

     See also: *note asec: XREFasec, *note secd: XREFsecd, *note sech:
     XREFsech.

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

     See also: *note acsc: XREFacsc, *note cscd: XREFcscd, *note csch:
     XREFcsch.

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

     See also: *note acot: XREFacot, *note cotd: XREFcotd, *note coth:
     XREFcoth.

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

     See also: *note sin: XREFsin, *note asind: XREFasind.

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

     See also: *note cos: XREFcos, *note acosd: XREFacosd.

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

     See also: *note tan: XREFtan, *note atand: XREFatand.

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

     See also: *note sec: XREFsec, *note asecd: XREFasecd.

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

     See also: *note csc: XREFcsc, *note acscd: XREFacscd.

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

     See also: *note cot: XREFcot, *note acotd: XREFacotd.

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

     See also: *note asinh: XREFasinh, *note cosh: XREFcosh, *note tanh:
     XREFtanh.

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

     See also: *note acosh: XREFacosh, *note sinh: XREFsinh, *note tanh:
     XREFtanh.

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

     See also: *note atanh: XREFatanh, *note sinh: XREFsinh, *note cosh:
     XREFcosh.

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

     See also: *note asech: XREFasech.

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

     See also: *note acsch: XREFacsch.

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

     See also: *note acoth: XREFacoth.

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

     See also: *note sinh: XREFsinh.

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

     See also: *note cosh: XREFcosh.

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

     See also: *note tanh: XREFtanh.

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

     See also: *note sech: XREFsech.

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

     See also: *note csch: XREFcsch.

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

     See also: *note coth: XREFcoth.

 -- : atan2 (Y, X)
     Compute atan (Y / X) for corresponding elements of Y and X.

     Y and X must match in size and orientation.  The signs of elements
     of Y and X are used to determine the quadrants of each resulting
     value.

     This function is equivalent to ‘arg (complex (X, Y))’.

     See also: *note tan: XREFtan, *note tand: XREFtand, *note tanh:
     XREFtanh, *note atanh: XREFatanh.

   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

 -- : sind (X)
     Compute the sine for each element of X in degrees.

     The function is more accurate than ‘sin’ for large values of X and
     for multiples of 180 degrees (‘X/180’ is an integer) where ‘sind’
     returns 0 rather than a small value on the order of eps.

     See also: *note asind: XREFasind, *note sin: XREFsin.

 -- : cosd (X)
     Compute the cosine for each element of X in degrees.

     The function is more accurate than ‘cos’ for large values of X and
     for multiples of 90 degrees (‘X = 90 + 180*n’ with n an integer)
     where ‘cosd’ returns 0 rather than a small value on the order of
     eps.

     See also: *note acosd: XREFacosd, *note cos: XREFcos.

 -- : 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: XREFatand, *note tan: XREFtan.

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

     See also: *note asecd: XREFasecd, *note sec: XREFsec.

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

     See also: *note acscd: XREFacscd, *note csc: XREFcsc.

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

     See also: *note acotd: XREFacotd, *note cot: XREFcot.

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

     See also: *note sind: XREFsind, *note asin: XREFasin.

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

     See also: *note cosd: XREFcosd, *note acos: XREFacos.

 -- : atand (X)
     Compute the inverse tangent in degrees for each element of X.

     See also: *note tand: XREFtand, *note atan: XREFatan.

 -- : atan2d (Y, X)
     Compute atan (Y / X) in degrees for corresponding elements from Y
     and X.

     See also: *note tand: XREFtand, *note atan2: XREFatan2.

 -- : asecd (X)
     Compute the inverse secant in degrees for each element of X.

     See also: *note secd: XREFsecd, *note asec: XREFasec.

 -- : acscd (X)
     Compute the inverse cosecant in degrees for each element of X.

     See also: *note cscd: XREFcscd, *note acsc: XREFacsc.

 -- : acotd (X)
     Compute the inverse cotangent in degrees for each element of X.

     See also: *note cotd: XREFcotd, *note acot: XREFacot.

   Finally, there are two trigonometric functions that calculate special
arguments with increased accuracy.

 -- : Y = sinpi (X)
     Compute sine (X * pi) for each element of X accurately.

     The ordinary ‘sin’ function uses IEEE floating point numbers and
     may produce results that are very close (within a few eps) of the
     correct value, but which are not exact.  The ‘sinpi’ function is
     more accurate and returns 0 exactly for integer values of X and
     +1/-1 for half-integer values (e.g., ..., -3/2, -1/2, 1/2, 3/2,
     ...).

     Example
     comparison of ‘sin’ and ‘sinpi’ for integer values of X

          sin ([0, 1, 2, 3] * pi)
          ⇒
               0   1.2246e-16  -2.4493e-16   3.6739e-16

          sinpi ([0, 1, 2, 3])
          ⇒
                 0   0   0   0

     See also: *note cospi: XREFcospi, *note sin: XREFsin.

 -- : Y = cospi (X)
     Compute cosine (X * pi) for each element of X accurately.

     The ordinary ‘cos’ function uses IEEE floating point numbers and
     may produce results that are very close (within a few eps) of the
     correct value, but which are not exact.  The ‘cospi’ function is
     more accurate and returns 0 exactly for half-integer values of X
     (e.g., ..., -3/2, -1/2, 1/2, 3/2, ...), and +1/-1 for integer
     values.

     Example
     comparison of ‘cos’ and ‘cospi’ for half-integer values of X

          cos ([-3/2, -1/2, 1/2, 3/2] * pi)
          ⇒
               -1.8370e-16   6.1232e-17   6.1232e-17  -1.8370e-16

          cospi ([-3/2, -1/2, 1/2, 3/2])
          ⇒
                 0   0   0   0

     See also: *note sinpi: XREFsinpi, *note cos: XREFcos.


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

17.4 Sums and Products
======================

 -- : sum (X)
 -- : sum (X, DIM)
 -- : sum (..., "native")
 -- : sum (..., "double")
 -- : sum (..., "extra")
     Sum of elements along dimension DIM.

     If DIM is omitted, it defaults to the first non-singleton
     dimension.

     The optional "type" input determines the class of the variable used
     for calculations.  By default, operations on floating point inputs
     (double or single) are performed in their native data type, while
     operations on integer, logical, and character data types are
     performed using doubles.  If the argument "native" is given, then
     the operation is performed in the same type as the original
     argument.

     For example:

          sum ([true, true])
             ⇒ 2
          sum ([true, true], "native")
             ⇒ true

     If "double" is given the sum is performed in double precision even
     for single precision inputs.

     For double precision inputs, the "extra" option will use a more
     accurate algorithm than straightforward summation.  For single
     precision inputs, "extra" is the same as "double".  For all other
     data type "extra" has no effect.

     See also: *note cumsum: XREFcumsum, *note sumsq: XREFsumsq, *note
     prod: XREFprod.

 -- : prod (X)
 -- : prod (X, DIM)
 -- : prod (..., "native")
 -- : prod (..., "double")
     Product of elements along dimension DIM.

     If DIM is omitted, it defaults to the first non-singleton
     dimension.

     The optional "type" input determines the class of the variable used
     for calculations.  If the argument "native" is given, then the
     operation is performed in the same type as the original argument,
     rather than the default double type.

     For example:

          prod ([true, true])
             ⇒ 1
          prod ([true, true], "native")
             ⇒ true

     On the contrary, if "double" is given, the operation is performed
     in double precision even for single precision inputs.

     See also: *note cumprod: XREFcumprod, *note sum: XREFsum.

 -- : cumsum (X)
 -- : cumsum (X, DIM)
 -- : cumsum (..., "native")
 -- : cumsum (..., "double")
     Cumulative sum of elements along dimension DIM.

     If DIM is omitted, it defaults to the first non-singleton
     dimension.  For example:

          cumsum ([1, 2; 3, 4; 5, 6])
             ⇒  1   2
                 4   6
                 9  12

     For an explanation of the optional parameters "native" and
     "double", *note ‘sum’: XREFsum.

     See also: *note sum: XREFsum, *note cumprod: XREFcumprod.

 -- : cumprod (X)
 -- : cumprod (X, DIM)
     Cumulative product of elements along dimension DIM.

     If DIM is omitted, it defaults to the first non-singleton
     dimension.  For example:

          cumprod ([1, 2; 3, 4; 5, 6])
             ⇒  1   2
                 3   8
                15  48

     See also: *note prod: XREFprod, *note cumsum: XREFcumsum.

 -- : sumsq (X)
 -- : 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: XREFsum, *note prod: XREFprod.


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

17.5 Utility Functions
======================

 -- : 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: XREFfloor, *note round: XREFround, *note
     fix: XREFfix.

 -- : 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: XREFceil, *note floor: XREFfloor, *note
     round: XREFround.

 -- : 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: XREFceil, *note round: XREFround, *note fix:
     XREFfix.

 -- : round (X)
     Return the integer nearest to X.

     If X is complex, return ‘round (real (X)) + round (imag (X)) * I’.
     If there are two nearest integers, return the one further away from
     zero.

          round ([-2.7, 2.7])
               ⇒ -3    3

     See also: *note ceil: XREFceil, *note floor: XREFfloor, *note fix:
     XREFfix, *note roundb: XREFroundb.

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

 -- : max (X)
 -- : max (X, [], DIM)
 -- : [W, IW] = max (X)
 -- : max (X, Y)
     Find maximum values in the array X.

     For a vector argument, return the maximum value.  For a matrix
     argument, return a row vector with the maximum value of each
     column.  For a multi-dimensional array, ‘max’ operates along the
     first non-singleton dimension.

     If the optional third argument DIM is present then operate along
     this dimension.  In this case the second argument is ignored and
     should be set to the empty matrix.

     For two inputs (X and Y), return the pairwise maximum according to
     the rules for *note Broadcasting::.

     Thus,

          max (max (X))

     returns the largest element of the 2-D 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 the magnitudes are identical, then the results are
     ordered by phase angle in the range (-pi, pi].  Hence,

          max ([-1 i 1 -i])
              ⇒ -1

     because all entries have magnitude 1, but -1 has the largest phase
     angle with value pi.

     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: XREFmin, *note cummax: XREFcummax, *note
     cummin: XREFcummin.

 -- : min (X)
 -- : min (X, [], DIM)
 -- : [W, IW] = min (X)
 -- : min (X, Y)
     Find minimum values in the array X.

     For a vector argument, return the minimum value.  For a matrix
     argument, return a row vector with the minimum value of each
     column.  For a multi-dimensional array, ‘min’ operates along the
     first non-singleton dimension.

     If the optional third argument DIM is present then operate along
     this dimension.  In this case the second argument is ignored and
     should be set to the empty matrix.

     For two inputs (X and Y), return the pairwise minimum according to
     the rules for *note Broadcasting::.

     Thus,

          min (min (X))

     returns the smallest element of the 2-D matrix 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 the magnitudes are identical, then the results are
     ordered by phase angle in the range (-pi, pi].  Hence,

          min ([-1 i 1 -i])
              ⇒ -i

     because all entries have magnitude 1, but -i has the smallest phase
     angle with value -pi/2.

     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: XREFmax, *note cummin: XREFcummin, *note
     cummax: XREFcummax.

 -- : cummax (X)
 -- : cummax (X, DIM)
 -- : [W, IW] = cummax (...)
     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

     If called with two output arguments the index of the maximum value
     is also returned.

          [w, iw] = cummax ([1 3 2 6 4 5])
          ⇒
          w =  1  3  3  6  6  6
          iw = 1  2  2  4  4  4

     See also: *note cummin: XREFcummin, *note max: XREFmax, *note min:
     XREFmin.

 -- : cummin (X)
 -- : cummin (X, DIM)
 -- : [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

     If called with two output arguments the index of the minimum value
     is also returned.

          [w, iw] = cummin ([5 4 6 2 3 1])
          ⇒
          w =  5  4  4  2  2  1
          iw = 1  2  2  4  4  6

     See also: *note cummax: XREFcummax, *note min: XREFmin, *note max:
     XREFmax.

 -- : hypot (X, Y)
 -- : 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 is 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.

 -- : DX = gradient (M)
 -- : [DX, DY, DZ, ...] = gradient (M)
 -- : [...] = gradient (M, S)
 -- : [...] = gradient (M, X, Y, Z, ...)
 -- : [...] = gradient (F, X0)
 -- : [...] = gradient (F, X0, S)
 -- : [...] = 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: XREFdiff, *note del2: XREFdel2.

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

     Implementation Note: 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’.
     Although, ‘dot’ is defined for integer arrays, the output may
     differ from the expected result due to the limited range of integer
     objects.

     See also: *note cross: XREFcross, *note divergence: XREFdivergence.

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

     If X and Y are matrices, the cross product is applied along the
     first dimension with three elements.

     The optional argument DIM forces the cross product to be calculated
     along the specified dimension.

     Example Code:

          cross ([1, 1, 0], [0, 1, 1])
            ⇒
                 1   -1   1

     See also: *note dot: XREFdot, *note curl: XREFcurl, *note
     divergence: XREFdivergence.

 -- : DIV = divergence (X, Y, Z, FX, FY, FZ)
 -- : DIV = divergence (FX, FY, FZ)
 -- : DIV = divergence (X, Y, FX, FY)
 -- : 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: XREFcurl, *note gradient: XREFgradient, *note
     del2: XREFdel2, *note dot: XREFdot.

 -- : [CX, CY, CZ, V] = curl (X, Y, Z, FX, FY, FZ)
 -- : [CZ, V] = curl (X, Y, FX, FY)
 -- : [...] = curl (FX, FY, FZ)
 -- : [...] = curl (FX, FY)
 -- : 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: XREFdivergence, *note gradient:
     XREFgradient, *note del2: XREFdel2, *note cross: XREFcross.

 -- : L = del2 (M)
 -- : L = del2 (M, H)
 -- : L = del2 (M, DX, DY, ...)

     Calculate the discrete Laplace operator.

     For a 2-dimensional matrix M this is defined as

                1    / d^2            d^2         \
          L  = --- * | ---  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.

     Dimensions with fewer than 3 data points are skipped.  Boundary
     points are calculated from the linear extrapolation of interior
     points.

     Example: Second derivative of 2*x^3

          f = @(x) 2*x.^3;
          dd = @(x) 12*x;
          x = 1:6;
          L = 4*del2 (f(x));
          assert (L, dd (x));

     See also: *note gradient: XREFgradient, *note diff: XREFdiff.

 -- : factorial (N)
     Return the factorial of N where N is a real non-negative 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’.
     Note that the factorial function grows large quite quickly, and
     even with double precision values overflow will occur if N > 171.
     For such cases consider ‘gammaln’.

     See also: *note prod: XREFprod, *note gamma: XREFgamma, *note
     gammaln: XREFgammaln.

 -- : PF = factor (Q)
 -- : [PF, N] = factor (Q)
     Return the prime factorization of Q.

     The prime factorization is defined as ‘prod (PF) == Q’ where every
     element of PF is a prime number.  If ‘Q == 1’, return 1.  The
     output PF is of the same numeric class as the input.

     With two output arguments, return the unique prime factors PF and
     their multiplicities.  That is, ‘prod (PF .^ N) == Q’.

     Implementation Note: The input Q must be less than ‘flintmax’ when
     the input is a floating-point class (double or single).

     See also: *note gcd: XREFgcd, *note lcm: XREFlcm, *note isprime:
     XREFisprime, *note primes: XREFprimes.

 -- : G = gcd (A1, A2, ...)
 -- : [G, V1, ...] = gcd (A1, A2, ...)
     Compute the greatest common divisor of A1, A2, ....

     All arguments must be the same size or scalar.  For arrays, 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 only unique
     up to a phase factor (multiplication by 1, -1, i, or -i), so an
     arbitrary greatest common divisor among the four possible is
     returned.

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

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

     Example code:

          gcd ([15, 9], [20, 18])
             ⇒  5  9

     See also: *note lcm: XREFlcm, *note factor: XREFfactor, *note
     isprime: XREFisprime.

 -- : lcm (X, Y)
 -- : lcm (X, Y, ...)
     Compute the least common multiple of X and Y, or of the list of all
     arguments.

     All elements must be numeric and of the same size or scalar.

     See also: *note factor: XREFfactor, *note gcd: XREFgcd, *note
     isprime: XREFisprime.

 -- : rem (X, Y)
     Return the remainder of the division ‘X / Y’.

     The remainder is 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 argument is complex.

     Programming Notes: When calculating with floating point numbers
     (double, single), values within a few eps of an integer will be
     rounded to that integer before computation for compatibility with
     MATLAB.  Any floating point integers greater than ‘flintmax’ (2^53
     for double) will not compute correctly.  For larger integer values
     convert the input to ‘uint64’ before calling this function.

     By convention,

          rem (X, 0) = NaN  if X is a floating point variable
          rem (X, 0) = 0    if X is an integer variable
          rem (X, Y)  returns a value with the signbit from X

     For the opposite conventions see the ‘mod’ function.  In general,
     ‘rem’ is best when computing the remainder after division of two
     _positive_ numbers.  For negative numbers, or when the values are
     periodic, ‘mod’ is a better choice.

     See also: *note mod: XREFmod.

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

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

     Programming Notes: When calculating with floating point numbers
     (double, single), values within a few eps of an integer will be
     rounded to that integer before computation for compatibility with
     MATLAB.  Any floating point integers greater than ‘flintmax’ (2^53
     for double) will not compute correctly.  For larger integer values
     convert the input to ‘uint64’ before calling this function.

     By convention,

          mod (X, 0) = X
          mod (X, Y)      returns a value with the signbit from Y

     For the opposite conventions see the ‘rem’ function.  In general,
     ‘mod’ is a better choice than ‘rem’ when any of the inputs are
     negative numbers or when the values are periodic.

     See also: *note rem: XREFrem.

 -- : P = primes (N)
     Return all primes up to N.

     The output data class (double, single, uint32, etc.) is the same as
     the input class of N.  The algorithm used is the Sieve of
     Eratosthenes.

     Note: For a specific number N of primes, call ‘list_primes (N)’.
     Alternatively, call ‘primes (N*log (K*N))(1:N)’ where K is about 5
     or 6.  This works because the distance from one prime to the next
     is proportional to the logarithm of the prime, on average.  On
     integrating, there are about N primes less than ‘N * log (5*N)’.

     See also: *note list_primes: XREFlist_primes, *note isprime:
     XREFisprime.

 -- : list_primes ()
 -- : list_primes (N)
     List the first N primes.

     If N is unspecified, the first 25 primes are listed.

     See also: *note primes: XREFprimes, *note isprime: XREFisprime.

 -- : sign (X)
     Compute the “signum” function.

     This is defined as

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

     For complex arguments, ‘sign’ returns ‘x ./ abs (X)’.

     Note that ‘sign (-0.0)’ is 0.  Although IEEE 754 floating point
     allows zero to be signed, 0.0 and -0.0 compare equal.  If you must
     test whether zero is signed, use the ‘signbit’ function.

     See also: *note signbit: XREFsignbit.

 -- : signbit (X)
     Return logical true if the value of X has its sign bit set and
     false otherwise.

     This behavior is consistent with the other logical functions.
     *Note Logical Values::.  The behavior differs from the C language
     function which returns nonzero if the sign bit is set.

     This is not the same as ‘x < 0.0’, because IEEE 754 floating point
     allows zero to be signed.  The comparison ‘-0.0 < 0.0’ is false,
     but ‘signbit (-0.0)’ will return a nonzero value.

     See also: *note sign: XREFsign.


File: octave.info,  Node: Special Functions,  Next: Rational Approximations,  Prev: Utility Functions,  Up: Arithmetic

17.6 Special Functions
======================

 -- : [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. Loss of significance by argument reduction, output may be
          inaccurate.

       5. Error—no computation, algorithm termination condition not met,
          return ‘NaN’.

 -- : J = besselj (ALPHA, X)
 -- : J = besselj (ALPHA, X, OPT)
 -- : [J, IERR] = besselj (...)
     Compute Bessel functions of the first kind.

     The order of the Bessel function ALPHA must be real.  The points
     for evaluation X may be complex.

     If the optional argument OPT is 1 or true, the result J is
     multiplied by ‘exp (-abs (imag (X)))’.

     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.

     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. Loss of significance by argument reduction, output may be
          inaccurate.

       5. Error—no computation, algorithm termination condition not met,
          return ‘NaN’.

     See also: *note bessely: XREFbessely, *note besseli: XREFbesseli,
     *note besselk: XREFbesselk, *note besselh: XREFbesselh.

 -- : Y = bessely (ALPHA, X)
 -- : Y = bessely (ALPHA, X, OPT)
 -- : [Y, IERR] = bessely (...)
     Compute Bessel functions of the second kind.

     The order of the Bessel function ALPHA must be real.  The points
     for evaluation X may be complex.

     If the optional argument OPT is 1 or true, the result Y is
     multiplied by ‘exp (-abs (imag (X)))’.

     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.

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

     See also: *note besselj: XREFbesselj, *note besseli: XREFbesseli,
     *note besselk: XREFbesselk, *note besselh: XREFbesselh.

 -- : I = besseli (ALPHA, X)
 -- : I = besseli (ALPHA, X, OPT)
 -- : [I, IERR] = besseli (...)
     Compute modified Bessel functions of the first kind.

     The order of the Bessel function ALPHA must be real.  The points
     for evaluation X may be complex.

     If the optional argument OPT is 1 or true, the result I is
     multiplied by ‘exp (-abs (real (X)))’.

     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.

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

     See also: *note besselk: XREFbesselk, *note besselj: XREFbesselj,
     *note bessely: XREFbessely, *note besselh: XREFbesselh.

 -- : K = besselk (ALPHA, X)
 -- : K = besselk (ALPHA, X, OPT)
 -- : [K, IERR] = besselk (...)

     Compute modified Bessel functions of the second kind.

     The order of the Bessel function ALPHA must be real.  The points
     for evaluation X may be complex.

     If the optional argument OPT is 1 or true, the result K is
     multiplied by ‘exp (X)’.

     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.

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

     See also: *note besseli: XREFbesseli, *note besselj: XREFbesselj,
     *note bessely: XREFbessely, *note besselh: XREFbesselh.

 -- : H = besselh (ALPHA, X)
 -- : H = besselh (ALPHA, K, X)
 -- : H = besselh (ALPHA, K, X, OPT)
 -- : [H, IERR] = besselh (...)
     Compute Bessel functions of the third kind (Hankel functions).

     The order of the Bessel function ALPHA must be real.  The kind of
     Hankel function is specified by K and may be either first (K = 1)
     or second (K = 2).  The default is Hankel functions of the first
     kind.  The points for evaluation X may be complex.

     If the optional argument OPT is 1 or true, 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.

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

     See also: *note besselj: XREFbesselj, *note bessely: XREFbessely,
     *note besseli: XREFbesseli, *note besselk: XREFbesselk.

 -- : beta (A, B)
     Compute the Beta function for real inputs A and B.

     The Beta function definition is

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

     The Beta function can grow quite large and it is often more useful
     to work with the logarithm of the output rather than the function
     directly.  *Note ‘betaln’: XREFbetaln, for computing the logarithm
     of the Beta function in an efficient manner.

     See also: *note betaln: XREFbetaln, *note betainc: XREFbetainc,
     *note betaincinv: XREFbetaincinv.

 -- : betainc (X, A, B)
 -- : betainc (X, A, B, TAIL)
     Compute the incomplete beta function.

     This is defined as

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

     with real X in the range [0,1].  The inputs A and B must be real
     and strictly positive (> 0).  If one of the inputs is not a scalar
     then the other inputs must be scalar or of compatible dimensions.

     By default, TAIL is "lower" and the incomplete beta function
     integrated from 0 to X is computed.  If TAIL is "upper" then the
     complementary function integrated from X to 1 is calculated.  The
     two choices are related by

     betainc (X, A, B, "upper") = 1 - betainc (X, A, B, "lower").

     ‘betainc’ uses a more sophisticated algorithm than subtraction to
     get numerically accurate results when the "lower" value is small.

     Reference: A. Cuyt, V. Brevik Petersen, B. Verdonk, H. Waadeland,
     W.B. Jones, ‘Handbook of Continued Fractions for Special
     Functions’, ch. 18.

     See also: *note beta: XREFbeta, *note betaincinv: XREFbetaincinv,
     *note betaln: XREFbetaln.

 -- : betaincinv (Y, A, B)
 -- : betaincinv (Y, A, B, "lower")
 -- : betaincinv (Y, A, B, "upper")
     Compute the inverse of the normalized incomplete beta function.

     The normalized incomplete beta function is defined as

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

     If two inputs are scalar, then ‘betaincinv (Y, A, B)’ is returned
     for each of the other inputs.

     If two or more inputs are not scalar, the sizes of them must agree,
     and ‘betaincinv’ is applied element-by-element.

     The variable Y must be in the interval [0,1], while A and B must be
     real and strictly positive.

     By default, TAIL is "lower" and the inverse of the incomplete beta
     function integrated from 0 to X is computed.  If TAIL is "upper"
     then the complementary function integrated from X to 1 is inverted.

     The function is computed by standard Newton’s method, by solving

          Y - betainc (X, A, B) = 0

     See also: *note betainc: XREFbetainc, *note beta: XREFbeta, *note
     betaln: XREFbetaln.

 -- : betaln (A, B)
     Compute the natural logarithm of the Beta function for real inputs
     A and B.

     ‘betaln’ is defined as

          betaln (a, b) = log (beta (a, b))

     and is calculated in a way to reduce the occurrence of underflow.

     The Beta function can grow quite large and it is often more useful
     to work with the logarithm of the output rather than the function
     directly.

     See also: *note beta: XREFbeta, *note betainc: XREFbetainc, *note
     betaincinv: XREFbetaincinv, *note gammaln: XREFgammaln.

 -- : bincoeff (N, K)
     Return the binomial coefficient of N and K.

     The binomial coefficient is 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: XREFnchoosek.

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

 -- : cosint (X)
     Compute the cosine integral function:

                      +oo
                     /
          Ci (x) = - | (cos (t)) / t dt
                     /
                    x

     An equivalent definition is

                                       x
                                      /
                                      |  cos (t) - 1
          Ci (x) = gamma + log (x) +  | -------------  dt
                                      |        t
                                      /
                                     0

     Reference:

     M. Abramowitz and I.A. Stegun, ‘Handbook of Mathematical
     Functions’, 1964.

     See also: *note sinint: XREFsinint, *note expint: XREFexpint, *note
     cos: XREFcos.

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

 -- : dawson (Z)
     Compute the Dawson (scaled imaginary error) function.

     The Dawson function is defined as

          (sqrt (pi) / 2) * exp (-z^2) * erfi (z)

     See also: *note erfc: XREFerfc, *note erf: XREFerf, *note erfcx:
     XREFerfcx, *note erfi: XREFerfi, *note erfinv: XREFerfinv, *note
     erfcinv: XREFerfcinv.

 -- : [SN, CN, DN, ERR] = ellipj (U, M)
 -- : [SN, CN, DN, ERR] = ellipj (U, M, TOL)
     Compute the Jacobi elliptic functions SN, CN, and DN of complex
     argument U and real parameter M.

     If M is a scalar, the results are the same size as U.  If U is a
     scalar, the results are the same size as M.  If U is a column
     vector and M is a row vector, the results are matrices with ‘length
     (U)’ rows and ‘length (M)’ columns.  Otherwise, U and M must
     conform in size and the results will be the same size as the
     inputs.

     The value of U may be complex.  The value of M must be 0 ≤ M ≤ 1.

     The optional input TOL is currently ignored (MATLAB uses this to
     allow faster, less accurate approximation).

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

       0. Normal return.

       1. Error—no computation, algorithm termination condition not met,
          return ‘NaN’.

     Reference: Milton Abramowitz and Irene A Stegun, ‘Handbook of
     Mathematical Functions’, Chapter 16 (Sections 16.4, 16.13, and
     16.15), Dover, 1965.

     See also: *note ellipke: XREFellipke.

 -- : K = ellipke (M)
 -- : K = ellipke (M, TOL)
 -- : [K, E] = ellipke (...)
     Compute complete elliptic integrals of the first K(M) and second
     E(M) kind.

     M must be a scalar or real array with -Inf ≤ M ≤ 1.

     The optional input TOL controls the stopping tolerance of the
     algorithm and defaults to ‘eps (class (M))’.  The tolerance can be
     increased to compute a faster, less accurate approximation.

     When called with one output only elliptic integrals of the first
     kind are returned.

     Mathematical Note:

     Elliptic integrals of the first kind are defined as

                   1
                  /               dt
          K (m) = | ------------------------------
                  / sqrt ((1 - t^2)*(1 - m*t^2))
                 0

     Elliptic integrals of the second kind are defined as

                   1
                  /  sqrt (1 - m*t^2)
          E (m) = |  ------------------ dt
                  /  sqrt (1 - t^2)
                 0

     Reference: Milton Abramowitz and Irene A. Stegun, ‘Handbook of
     Mathematical Functions’, Chapter 17, Dover, 1965.

     See also: *note ellipj: XREFellipj.

 -- : erf (Z)
     Compute the error function.

     The error function is defined as

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

     See also: *note erfc: XREFerfc, *note erfcx: XREFerfcx, *note erfi:
     XREFerfi, *note dawson: XREFdawson, *note erfinv: XREFerfinv, *note
     erfcinv: XREFerfcinv.

 -- : erfc (Z)
     Compute the complementary error function.

     The complementary error function is defined as ‘1 - erf (Z)’.

     See also: *note erfcinv: XREFerfcinv, *note erfcx: XREFerfcx, *note
     erfi: XREFerfi, *note dawson: XREFdawson, *note erf: XREFerf, *note
     erfinv: XREFerfinv.

 -- : erfcx (Z)
     Compute the scaled complementary error function.

     The scaled complementary error function is defined as

          exp (z^2) * erfc (z)

     See also: *note erfc: XREFerfc, *note erf: XREFerf, *note erfi:
     XREFerfi, *note dawson: XREFdawson, *note erfinv: XREFerfinv, *note
     erfcinv: XREFerfcinv.

 -- : erfi (Z)
     Compute the imaginary error function.

     The imaginary error function is defined as

          -i * erf (i*z)

     See also: *note erfc: XREFerfc, *note erf: XREFerf, *note erfcx:
     XREFerfcx, *note dawson: XREFdawson, *note erfinv: XREFerfinv,
     *note erfcinv: XREFerfcinv.

 -- : erfinv (X)
     Compute the inverse error function.

     The inverse error function is defined such that

          erf (Y) == X

     See also: *note erf: XREFerf, *note erfc: XREFerfc, *note erfcx:
     XREFerfcx, *note erfi: XREFerfi, *note dawson: XREFdawson, *note
     erfcinv: XREFerfcinv.

 -- : erfcinv (X)
     Compute the inverse complementary error function.

     The inverse complementary error function is defined such that

          erfc (Y) == X

     See also: *note erfc: XREFerfc, *note erf: XREFerf, *note erfcx:
     XREFerfcx, *note erfi: XREFerfi, *note dawson: XREFdawson, *note
     erfinv: XREFerfinv.

 -- : expint (X)
     Compute the exponential integral.

     The exponential integral is defined as:

                     +oo
                    /
                    | exp (-t)
          E_1 (x) = | -------- dt
                    |    t
                    /
                   x

     Note: For compatibility, this function uses the MATLAB definition
     of the exponential integral.  Most other sources refer to this
     particular value as E_1 (x), and the exponential integral as

                      +oo
                     /
                     | exp (-t)
          Ei (x) = - | -------- dt
                     |    t
                     /
                   -x

     The two definitions are related, for positive real values of X, by
     ‘E_1 (-x) = -Ei (x) - i*pi’.

     References:

     M. Abramowitz and I.A. Stegun, ‘Handbook of Mathematical
     Functions’, 1964.

     N. Bleistein and R.A. Handelsman, ‘Asymptotic expansions of
     integrals’, 1986.

     See also: *note cosint: XREFcosint, *note sinint: XREFsinint, *note
     exp: XREFexp.

 -- : gamma (Z)
     Compute the Gamma function.

     The Gamma function is defined as

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

     Programming Note: The gamma function can grow quite large even for
     small input values.  In many cases it may be preferable to use the
     natural logarithm of the gamma function (‘gammaln’) in calculations
     to minimize loss of precision.  The final result is then ‘exp
     (RESULT_USING_GAMMALN).’

     See also: *note gammainc: XREFgammainc, *note gammaln: XREFgammaln,
     *note factorial: XREFfactorial.

 -- : gammainc (X, A)
 -- : gammainc (X, A, TAIL)
     Compute the normalized incomplete gamma function.

     This is defined as

                                          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 then the sizes of X and A must agree,
     and ‘gammainc’ is applied element-by-element.  The elements of A
     must be non-negative.

     By default, TAIL is "lower" and the incomplete gamma function
     integrated from 0 to X is computed.  If TAIL is "upper" then the
     complementary function integrated from X to infinity is calculated.

     If TAIL is "scaledlower", then the lower incomplete gamma function
     is multiplied by gamma(a+1)*exp(x)/(x^a).  If TAIL is
     "scaledupper", then the upper incomplete gamma function is
     multiplied by the same quantity.

     References:

     M. Abramowitz and I.A. Stegun, ‘Handbook of mathematical
     functions’, Dover publications, Inc., 1972.

     W. Gautschi, ‘A computational procedure for incomplete gamma
     functions’, ACM Trans. Math Software, pp. 466–481, Vol 5, No. 4,
     2012.

     W. H. Press, S. A. Teukolsky, W. T. Vetterling, and B. P. Flannery,
     ‘Numerical Recipes in Fortran 77’, ch. 6.2, Vol 1, 1992.

     See also: *note gamma: XREFgamma, *note gammaincinv:
     XREFgammaincinv, *note gammaln: XREFgammaln.

 -- : gammaincinv (Y, A)
 -- : gammaincinv (Y, A, TAIL)
     Compute the inverse of the normalized incomplete gamma function.

     The normalized incomplete gamma function is defined as

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

     and ‘gammaincinv (gammainc (X, A), A) = X’ for each non-negative
     value of X.  If A is scalar then ‘gammaincinv (Y, A)’ is returned
     for each element of Y and vice versa.

     If neither Y nor A is scalar then the sizes of Y and A must agree,
     and ‘gammaincinv’ is applied element-by-element.  The variable Y
     must be in the interval [0,1] while A must be real and positive.

     By default, TAIL is "lower" and the inverse of the incomplete gamma
     function integrated from 0 to X is computed.  If TAIL is "upper",
     then the complementary function integrated from X to infinity is
     inverted.

     The function is computed with Newton’s method by solving

          Y - gammainc (X, A) = 0

     Reference: A. Gil, J. Segura, and N. M. Temme, ‘Efficient and
     accurate algorithms for the computation and inversion of the
     incomplete gamma function ratios’, SIAM J. Sci. Computing, pp.
     A2965–A2981, Vol 34, 2012.

     See also: *note gammainc: XREFgammainc, *note gamma: XREFgamma,
     *note gammaln: XREFgammaln.

 -- : L = legendre (N, X)
 -- : L = legendre (N, X, NORMALIZATION)
     Compute the associated Legendre function of degree N and order M =
     0 ... N.

     The value N must be a real non-negative integer.

     X is a vector with real-valued elements in the range [-1, 1].

     The optional argument NORMALIZATION may be one of "unnorm", "sch",
     or "norm".  The default if no normalization is given is "unnorm".

     When the optional argument NORMALIZATION is "unnorm", compute the
     associated 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 associated 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

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

     When the optional argument NORMALIZATION is "norm", compute the
     fully normalized associated Legendre function.  The fully
     normalized associated Legendre function is related to the
     unnormalized associated 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)!

 -- : gammaln (X)
 -- : lgamma (X)
     Return the natural logarithm of the gamma function of X.

     See also: *note gamma: XREFgamma, *note gammainc: XREFgammainc.

 -- : psi (Z)
 -- : psi (K, Z)
     Compute the psi (polygamma) function.

     The polygamma functions are the Kth derivative of the logarithm of
     the gamma function.  If unspecified, K defaults to zero.  A value
     of zero computes the digamma function, a value of 1, the trigamma
     function, and so on.

     The digamma function is defined:

          psi (z) = d (log (gamma (z))) / dx

     When computing the digamma function (when K equals zero), Z can
     have any value real or complex value.  However, for polygamma
     functions (K higher than 0), Z must be real and non-negative.

     See also: *note gamma: XREFgamma, *note gammainc: XREFgammainc,
     *note gammaln: XREFgammaln.

 -- : sinint (X)
     Compute the sine integral function:

                     x
                    /
          Si (x) =  | sin (t) / t dt
                    /
                   0

     Reference: M. Abramowitz and I.A. Stegun, ‘Handbook of Mathematical
     Functions’, 1964.

     See also: *note cosint: XREFcosint, *note expint: XREFexpint, *note
     sin: XREFsin.


File: octave.info,  Node: Rational Approximations,  Next: Coordinate Transformations,  Prev: Special Functions,  Up: Arithmetic

17.7 Rational Approximations
============================

 -- : S = rat (X)
 -- : S = rat (X, TOL)
 -- : [N, D] = rat (...)

     Find a rational approximation of X to within the tolerance defined
     by TOL.

     If unspecified, the default tolerance is ‘1e-6 * norm (X(:), 1)’.

     When called with one output argument, return a string containing a
     continued fraction expansion (multiple terms).

     When called with two output arguments, return numeric matrices for
     the numerator and denominator of a fractional representation of X
     such that ‘X = N ./ D’.

     For example:

          s = rat (pi)
          ⇒ s = 3 + 1/(7 + 1/16)

          [n, d] = rat (pi)
          ⇒ n =  355
          ⇒ d =  113

          n / d - pi
          ⇒ 0.00000026676

     Programming Note: With one output ‘rat’ produces a string which is
     a continued fraction expansion.  To produce a string which is a
     simple fraction (one numerator, one denominator) use ‘rats’.

     See also: *note rats: XREFrats, *note format: XREFformat.

 -- : S = rats (X)
 -- : S = rats (X, LEN)
     Convert X into a rational approximation represented as a string.

     A rational approximation to a floating point number is a simple
     fraction with numerator N and denominator D such that ‘X = N/D’.

     The optional second argument defines the maximum length of the
     string representing the elements of X.  By default, LEN is 9.

     If the length of the smallest possible rational approximation
     exceeds LEN, an asterisk (*) padded with spaces will be returned
     instead.

     Example conversion from matrix to string, and back again.

          r = rats (hilb (4));
          x = str2num (r)

     See also: *note rat: XREFrat, *note format: XREFformat.


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

17.8 Coordinate Transformations
===============================

 -- : [THETA, R] = cart2pol (X, Y)
 -- : [THETA, R, Z] = cart2pol (X, Y, Z)
 -- : [THETA, R] = cart2pol (C)
 -- : [THETA, R, Z] = cart2pol (C)

     Transform Cartesian coordinates to polar or cylindrical
     coordinates.

     The inputs 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 pair (X, Y) or triplet (X, Y, Z).

     The outputs THETA, R (, and Z) match the shape of the inputs.  For
     a matrix input C the outputs will be column vectors with rows
     corresponding to the rows of the input matrix.

     THETA describes the angle relative to the positive x-axis measured
     in the xy-plane.

     R is the distance to the z-axis (0, 0, z).

     Z, if present, is unchanged by the transformation.

     The coordinate transformation is computed using:

          THETA = arctan (Y / X)
          R = sqrt (X^2 + Y^2)
          Z = Z

     Note: For MATLAB compatibility, this function no longer returns a
     full coordinate matrix when called with a single return argument.

     See also: *note pol2cart: XREFpol2cart, *note cart2sph:
     XREFcart2sph, *note sph2cart: XREFsph2cart.

 -- : [X, Y] = pol2cart (THETA, R)
 -- : [X, Y, Z] = pol2cart (THETA, R, Z)
 -- : [X, Y] = pol2cart (P)
 -- : [X, Y, Z] = pol2cart (P)
     Transform polar or cylindrical coordinates to Cartesian
     coordinates.

     The inputs THETA, R, (and Z) must be the same shape, or scalar.  If
     called with a single matrix argument then each row of P represents
     the polar coordinate pair (THETA, R) or the cylindrical triplet
     (THETA, R, Z).

     The outputs X, Y (, and Z) match the shape of the inputs.  For a
     matrix input P the outputs will be column vectors with rows
     corresponding to the rows of the input matrix.

     THETA describes the angle relative to the positive x-axis measured
     in the xy-plane.

     R is the distance to the z-axis (0, 0, z).

     Z, if present, is unchanged by the transformation.

     The coordinate transformation is computed using:

          X = R * cos (THETA)
          Y = R * sin (THETA)
          Z = Z

     Note: For MATLAB compatibility, this function no longer returns a
     full coordinate matrix when called with a single return argument.

     See also: *note cart2pol: XREFcart2pol, *note sph2cart:
     XREFsph2cart, *note cart2sph: XREFcart2sph.

 -- : [THETA, PHI, R] = cart2sph (X, Y, Z)
 -- : [THETA, PHI, R] = cart2sph (C)
     Transform Cartesian coordinates to spherical coordinates.

     The inputs X, Y, and Z must be the same shape, or scalar.  If
     called with a single matrix argument then each row of C must
     represent a Cartesian coordinate triplet (X, Y, Z).

     The outputs THETA, PHI, R match the shape of the inputs.  For a
     matrix input C the outputs will be column vectors with rows
     corresponding to the rows of the input matrix.

     THETA describes the azimuth angle relative to the positive x-axis
     measured in the xy-plane.

     PHI is the elevation angle measured relative to the xy-plane.

     R is the distance to the origin (0, 0, 0).

     The coordinate transformation is computed using:

          THETA = arctan (Y / X)
          PHI = arctan (Z / sqrt (X^2 + Y^2))
          R = sqrt (X^2 + Y^2 + Z^2)

     Note: For MATLAB compatibility, this function no longer returns a
     full coordinate matrix when called with a single return argument.

     See also: *note sph2cart: XREFsph2cart, *note cart2pol:
     XREFcart2pol, *note pol2cart: XREFpol2cart.

 -- : [X, Y, Z] = sph2cart (THETA, PHI, R)
 -- : [X, Y, Z] = sph2cart (S)
     Transform spherical coordinates to Cartesian coordinates.

     The inputs THETA, PHI, and R must be the same shape, or scalar.  If
     called with a single matrix argument then each row of S must
     represent a spherical coordinate triplet (THETA, PHI, R).

     The outputs X, Y, Z match the shape of the inputs.  For a matrix
     input S the outputs are column vectors with rows corresponding to
     the rows of the input matrix.

     THETA describes the azimuth angle relative to the positive x-axis
     measured in the xy-plane.

     PHI is the elevation angle measured relative to the xy-plane.

     R is the distance to the origin (0, 0, 0).

     The coordinate transformation is computed using:

          X = r * cos (PHI) * cos (THETA)
          Y = r * cos (PHI) * sin (THETA)
          Z = r * sin (PHI)

     Note: For MATLAB compatibility, this function no longer returns a
     full coordinate matrix when called with a single return argument.

     See also: *note cart2sph: XREFcart2sph, *note pol2cart:
     XREFpol2cart, *note cart2pol: XREFcart2pol.


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

17.9 Mathematical Constants
===========================

 -- : e
 -- : e (N)
 -- : e (N, M)
 -- : e (N, M, K, ...)
 -- : 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".

     See also: *note log: XREFlog, *note exp: XREFexp, *note pi: XREFpi,
     *note I: XREFI.

 -- : pi
 -- : pi (N)
 -- : pi (N, M)
 -- : pi (N, M, K, ...)
 -- : 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".

     See also: *note e: XREFe, *note I: XREFI.

 -- : I
 -- : I (N)
 -- : I (N, M)
 -- : I (N, M, K, ...)
 -- : 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".

     See also: *note e: XREFe, *note pi: XREFpi, *note log: XREFlog,
     *note exp: XREFexp.

 -- : Inf
 -- : Inf (N)
 -- : Inf (N, M)
 -- : Inf (N, M, K, ...)
 -- : 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 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: XREFisinf, *note NaN: XREFNaN.

 -- : VAL = NaN
 -- : VAL = NaN (N)
 -- : VAL = NaN (N, M)
 -- : VAL = NaN (N, M, K, ...)
 -- : VAL = NaN (..., "LIKE", VAR))
 -- : VAL = 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.

     If a variable VAR is specified after "like", the output VAL will
     have the same data type, complexity, and sparsity as VAR.

     The optional argument CLASS specifies the return type and may be
     either "double" or "single".

     See also: *note isnan: XREFisnan, *note Inf: XREFInf.

 -- : eps
 -- : eps (X)
 -- : eps (N, M)
 -- : eps (N, M, K, ...)
 -- : 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".

     See also: *note realmax: XREFrealmax, *note realmin: XREFrealmin,
     *note intmax: XREFintmax, *note flintmax: XREFflintmax.

 -- : realmax
 -- : realmax (N)
 -- : realmax (N, M)
 -- : realmax (N, M, K, ...)
 -- : 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: XREFrealmin, *note intmax: XREFintmax,
     *note flintmax: XREFflintmax, *note eps: XREFeps.

 -- : realmin
 -- : realmin (N)
 -- : realmin (N, M)
 -- : realmin (N, M, K, ...)
 -- : 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: XREFrealmax, *note intmin: XREFintmin,
     *note eps: XREFeps.


File: octave.info,  Node: Linear Algebra,  Next: Vectorization and Faster Code Execution,  Prev: Arithmetic,  Up: Top

18 Linear Algebra
*****************

This chapter documents the linear algebra functions provided in 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.  The ‘LAPACK Users’ Guide’ is
available at: ‘http://www.netlib.org/lapack/lug/’

   A common text for engineering courses is G. Strang, ‘Linear Algebra
and Its Applications, 4th Edition’.  It has become a widespread
reference for linear algebra.  An alternative is P. Lax ‘Linear Algebra
and Its Applications’, and also is a good choice.  It claims to be
suitable for high school students with substantial mathematical
interests as well as first-year undergraduates.

* 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.  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 solved or a matrix
inverse is formed is given by:

  1. If the matrix is upper or lower triangular sparse use 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 make certain that the matrix is Hermitian.  However,
the attempt to factorize the matrix will quickly detect 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
===========================

 -- : AA = balance (A)
 -- : AA = balance (A, OPT)
 -- : [DD, AA] = balance (A, OPT)
 -- : [D, P, AA] = balance (A, OPT)
 -- : [CC, DD, AA, BB] = balance (A, B, OPT)

     Balance the matrix A to reduce numerical errors in future
     calculations.

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

 -- : BW = bandwidth (A, TYPE)
 -- : [LOWER, UPPER] = bandwidth (A)
     Compute the bandwidth of A.

     The TYPE argument is the string "lower" for the lower bandwidth and
     "upper" for the upper bandwidth.  If no TYPE is specified return
     both the lower and upper bandwidth of A.

     The lower/upper bandwidth of a matrix is the number of
     subdiagonals/superdiagonals with nonzero entries.

     See also: *note isbanded: XREFisbanded, *note isdiag: XREFisdiag,
     *note istril: XREFistril, *note istriu: XREFistriu.

 -- : cond (A)
 -- : cond (A, P)
     Compute the P-norm condition number of a matrix with respect to
     inversion.

     ‘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.  For a full discussion
     of possible P values, *note ‘norm’: XREFnorm.

     The condition number of a matrix quantifies the sensitivity of the
     matrix inversion operation when small changes are made to matrix
     elements.  Ideally the condition number will be close to 1.  When
     the number is large this indicates small changes (such as underflow
     or round-off error) will produce large changes in the resulting
     output.  In such cases the solution results from numerical
     computing are not likely to be accurate.

     See also: *note condest: XREFcondest, *note rcond: XREFrcond, *note
     condeig: XREFcondeig, *note norm: XREFnorm, *note svd: XREFsvd.

 -- : C = condeig (A)
 -- : [V, LAMBDA, C] = condeig (A)
     Compute condition numbers of a matrix with respect to eigenvalues.

     The condition numbers are the reciprocals of the cosines of the
     angles between the left and right eigenvectors; Large values
     indicate that the matrix has multiple distinct eigenvalues.

     The input A must be a square numeric matrix.

     The outputs are:

        • C is a vector of condition numbers for the eigenvalues of A.

        • V is the matrix of right eigenvectors of A.  The result is
          equivalent to calling ‘[V, LAMBDA] = eig (A)’.

        • LAMBDA is the diagonal matrix of eigenvalues of A.  The result
          is equivalent to calling ‘[V, LAMBDA] = eig (A)’.

     Example

          a = [1, 2; 3, 4];
          c = condeig (a)
            ⇒ c =
                 1.0150
                 1.0150

     See also: *note eig: XREFeig, *note cond: XREFcond, *note balance:
     XREFbalance.

 -- : det (A)
 -- : [D, RCOND] = det (A)
     Compute the determinant of A.

     Return an estimate of the reciprocal condition number if requested.

     Programming Notes: 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: XREFcond, *note condest: XREFcondest, *note
     rcond: XREFrcond.

 -- : LAMBDA = eig (A)
 -- : LAMBDA = eig (A, B)
 -- : [V, LAMBDA] = eig (A)
 -- : [V, LAMBDA] = eig (A, B)
 -- : [V, LAMBDA, W] = eig (A)
 -- : [V, LAMBDA, W] = eig (A, B)
 -- : [...] = eig (A, BALANCEOPTION)
 -- : [...] = eig (A, B, ALGORITHM)
 -- : [...] = eig (..., EIGVALOPTION)
     Compute the eigenvalues (LAMBDA) and optionally the right
     eigenvectors (V) and the left eigenvectors (W) of a matrix or pair
     of matrices.

     The flag BALANCEOPTION can be one of:

     "balance" (default)
          Preliminary balancing is on.

     "nobalance"
          Disables preliminary balancing.

     The flag EIGVALOPTION can be one of:

     "matrix"
          Return the eigenvalues in a diagonal matrix.  (default if 2 or
          3 outputs are requested)

     "vector"
          Return the eigenvalues in a column vector.  (default if only 1
          output is requested, e.g., LAMBDA = eig (A))

     The flag ALGORITHM can be one of:

     "chol"
          Use the Cholesky factorization of B. (default if A is
          symmetric (Hermitian) and B is symmetric (Hermitian) positive
          definite)

     "qz"
          Use the QZ algorithm.  (used whenever A or B are not
          symmetric)

                            no flag           chol              qz
     -----------------------------------------------------------------------------
     both are symmetric     "chol"            "chol"            "qz"
     at least one is not    "qz"              "qz"              "qz"
     symmetric

     The eigenvalues returned by ‘eig’ are not ordered.

     See also: *note eigs: XREFeigs, *note svd: XREFsvd.

 -- : G = givens (X, Y)
 -- : [C, S] = givens (X, Y)
     Compute the Givens rotation matrix G.

     The Givens matrix is a 2-by-2 orthogonal matrix

          G = [ C , S
               -S', C]

     such that

          G * [X; Y] = [*; 0]

     with X and Y scalars.

     If two output arguments are requested, return the factors C and S
     rather than the Givens rotation matrix.

     For example:

          givens (1, 1)
             ⇒   0.70711   0.70711
                 -0.70711   0.70711

     Note: The Givens matrix represents a counterclockwise rotation of a
     2-D plane and can be used to introduce zeros into a matrix prior to
     complete factorization.

     See also: *note planerot: XREFplanerot, *note qr: XREFqr.

 -- : S = gsvd (A, B)
 -- : [U, V, X, C, S] = gsvd (A, B)
 -- : [U, V, X, C, S] = gsvd (A, B, 0)
     Compute the generalized singular value decomposition of (A, B).

     The generalized singular value decomposition is defined by the
     following relations:

          A = U*C*X'
          B = V*S*X'
          C'*C + S'*S = eye (columns (A))

     The function ‘gsvd’ normally returns just the vector of generalized
     singular values ‘sqrt (diag (C'*C) ./ diag (S'*S))’.  If asked for
     five return values, it also computes U, V, X, and C.

     If the optional third input is present, ‘gsvd’ constructs the
     "economy-sized" decomposition where the number of columns of U, V
     and the number of rows of C, S is less than or equal to the number
     of columns of A.  This option is not yet implemented.

     Programming Note: the code is a wrapper to the corresponding LAPACK
     dggsvd and zggsvd routines.  If matrices A and B are _both_ rank
     deficient then LAPACK will return an incorrect factorization.
     Programmers should avoid this combination.

     See also: *note svd: XREFsvd.

 -- : [G, Y] = planerot (X)
     Compute the Givens rotation matrix for the two-element column
     vector X.

     The Givens matrix is a 2-by-2 orthogonal matrix

          G = [ C , S
               -S', C]

     such that

          Y = G * [X(1); X(2)] ≡ [*; 0]

     Note: The Givens matrix represents a counterclockwise rotation of a
     2-D plane and can be used to introduce zeros into a matrix prior to
     complete factorization.

     See also: *note givens: XREFgivens, *note qr: XREFqr.

 -- : X = inv (A)
 -- : [X, RCOND] = inv (A)
 -- : [...] = inverse (...)
     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.

     ‘inverse’ is an alias and may be used identically in place of
     ‘inv’.

     See also: *note ldivide: XREFldivide, *note rdivide: XREFrdivide,
     *note pinv: XREFpinv.

 -- : X = linsolve (A, B)
 -- : X = linsolve (A, B, OPTS)
 -- : [X, R] = linsolve (...)
     Solve the linear system ‘A*x = b’.

     With no options, this function is equivalent to the left division
     operator (‘x = A \ b’) or the matrix-left-divide function
     (‘x = mldivide (A, b)’).

     Octave ordinarily examines the properties of the matrix A and
     chooses a solver that best matches the matrix.  By passing a
     structure OPTS to ‘linsolve’ you can inform Octave directly about
     the matrix A.  In this case Octave will skip the matrix examination
     and proceed directly to solving the linear system.

     *Warning:* If the matrix A does not have the properties listed in
     the OPTS structure then the result will not be accurate AND no
     warning will be given.  When in doubt, let Octave examine the
     matrix and choose the appropriate solver as this step takes little
     time and the result is cached so that it is only done once per
     linear system.

     Possible OPTS fields (set value to true/false):

     LT
          A is lower triangular

     UT
          A is upper triangular

     UHESS
          A is upper Hessenberg (currently makes no difference)

     SYM
          A is symmetric or complex Hermitian (currently makes no
          difference)

     POSDEF
          A is positive definite

     RECT
          A is general rectangular (currently makes no difference)

     TRANSA
          Solve ‘A'*x = b’ if true rather than ‘A*x = b’

     The optional second output R is the inverse condition number of A
     (zero if matrix is singular).

     See also: *note mldivide: XREFmldivide, *note matrix_type:
     XREFmatrix_type, *note rcond: XREFrcond.

 -- : TYPE = matrix_type (A)
 -- : TYPE = matrix_type (A, "nocompute")
 -- : A = matrix_type (A, TYPE)
 -- : A = matrix_type (A, "upper", PERM)
 -- : A = matrix_type (A, "lower", PERM)
 -- : 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.

 -- : norm (A)
 -- : norm (A, P)
 -- : norm (A, P, OPT)
     Compute the p-norm of the matrix A.

     If the second argument is not given, ‘p = 2’ is used.

     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 normest: XREFnormest, *note normest1: XREFnormest1,
     *note vecnorm: XREFvecnorm, *note cond: XREFcond, *note svd:
     XREFsvd.

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

     The dimension of the null space Z 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, 0)) * eps

     See also: *note orth: XREForth, *note svd: XREFsvd.

 -- : orth (A)
 -- : 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: XREFnull.

 -- : [Y, H] = mgorth (X, V)
     Orthogonalize a given column vector X with respect to a set of
     orthonormal vectors comprising the columns of V using the modified
     Gram-Schmidt method.

     On exit, Y is a unit vector such that:

            norm (Y) = 1
            V' * Y = 0
            X = [V, Y]*H'

 -- : pinv (X)
 -- : pinv (X, TOL)
     Return the Moore-Penrose pseudoinverse of X.

     Singular values less than TOL are ignored.

     If the second argument is omitted, it is taken to be

          tol = max ([rows(X), columns(X)]) * norm (X) * eps

     See also: *note inv: XREFinv, *note ldivide: XREFldivide.

 -- : rank (A)
 -- : rank (A, TOL)
     Compute the rank of matrix 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.

     The rank of a matrix is the number of linearly independent rows or
     columns and equals the dimension of the row and column space.  The
     function ‘orth’ may be used to compute an orthonormal basis of the
     column space.

     For testing if a system ‘A*X = B’ of linear equations is solvable,
     one can use

          rank (A) == rank ([A B])

     In this case, ‘X = A \ B’ finds a particular solution X.  The
     general solution is X plus the null space of matrix A.  The
     function ‘null’ may be used to compute a basis of the null space.

     Example:

          A = [1 2 3
               4 5 6
               7 8 9];
          rank (A)
            ⇒ 2

     In this example, the number of linearly independent rows is only 2
     because the final row is a linear combination of the first two
     rows:

          A(3,:) == -A(1,:) + 2 * A(2,:)

     See also: *note null: XREFnull, *note orth: XREForth, *note sprank:
     XREFsprank, *note svd: XREFsvd, *note eps: XREFeps.

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

     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: XREFcond, *note condest: XREFcondest.

 -- : trace (A)
     Compute the trace of A, the sum of the elements along the main
     diagonal.

     The implementation is straightforward: ‘sum (diag (A))’.

     See also: *note eig: XREFeig.

 -- : rref (A)
 -- : rref (A, TOL)
 -- : [R, K] = rref (...)
     Return the reduced row echelon form of A.

     TOL defaults to ‘eps * max (size (A)) * norm (A, inf)’.

     The optional return argument K contains the vector of "bound
     variables", which are those columns on which elimination has been
     performed.

 -- : N = vecnorm (A)
 -- : N = vecnorm (A, P)
 -- : N = vecnorm (A, P, DIM)
     Return the vector p-norm of the elements of array A along dimension
     DIM.

     The p-norm of a vector is defined as

          P-NORM (A, P) = sum (abs (A) .^ P)) ^ (1/P)

     The input P must be a positive scalar.  If omitted it defaults to 2
     (Euclidean norm or distance).  Other special values of P are 1
     (Manhattan norm, sum of absolute values) and ‘Inf’ (absolute value
     of largest element).

     The input DIM specifies the dimension of the array on which the
     function operates and must be a positive integer.  If omitted the
     first non-singleton dimension is used.

     See also: *note norm: XREFnorm.


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

18.3 Matrix Factorizations
==========================

 -- : R = chol (A)
 -- : [R, P] = chol (A)
 -- : [R, P, Q] = chol (A)
 -- : [R, P, Q] = chol (A, "vector")
 -- : [L, ...] = chol (..., "lower")
 -- : [R, ...] = chol (..., "upper")
     Compute the upper Cholesky factor, R, of the real symmetric or
     complex Hermitian positive definite matrix A.

     The upper Cholesky factor R is computed by using the upper
     triangular part of matrix A and is defined by

          R' * R = A.

     Calling ‘chol’ using the optional "upper" flag has the same
     behavior.  In contrast, using the optional "lower" flag, ‘chol’
     returns the lower triangular factorization, computed by using the
     lower triangular part of matrix A, such that

          L * L' = A.

     Called with one output argument ‘chol’ fails if matrix A is not
     positive definite.  Note that if matrix A is not real symmetric or
     complex Hermitian then the lower triangular part is considered to
     be the (complex conjugate) transpose of the upper triangular part,
     or vice versa, given the "lower" flag.

     Called with two or more output arguments P flags whether the matrix
     A was positive definite and ‘chol’ does not fail.  A zero value of
     P indicates that matrix A is positive definite and R gives the
     factorization.  Otherwise, P will have a positive value.

     If called with three output arguments matrix A must be sparse and a
     sparsity preserving row/column permutation is applied to matrix 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 optional flag "vector", Q will be
     returned as a vector such that

          R' * R = A(Q, Q).

     In general the lower triangular factorization is significantly
     faster for sparse matrices.

     See also: *note hess: XREFhess, *note lu: XREFlu, *note qr: XREFqr,
     *note qz: XREFqz, *note schur: XREFschur, *note svd: XREFsvd, *note
     ichol: XREFichol, *note cholinv: XREFcholinv, *note chol2inv:
     XREFchol2inv, *note cholupdate: XREFcholupdate, *note cholinsert:
     XREFcholinsert, *note choldelete: XREFcholdelete, *note cholshift:
     XREFcholshift.

 -- : cholinv (A)
     Compute the inverse of the symmetric positive definite matrix A
     using the Cholesky factorization.

     See also: *note chol: XREFchol, *note chol2inv: XREFchol2inv, *note
     inv: XREFinv.

 -- : 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: XREFchol, *note cholinv: XREFcholinv, *note
     inv: XREFinv.

 -- : [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: XREFchol, *note cholinsert: XREFcholinsert,
     *note choldelete: XREFcholdelete, *note cholshift: XREFcholshift.

 -- : R1 = cholinsert (R, J, U)
 -- : [R1, INFO] = cholinsert (R, J, U)
     Update a Cholesky factorization given a row or column to insert in
     the original factored matrix.

     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: XREFchol, *note cholupdate: XREFcholupdate,
     *note choldelete: XREFcholdelete, *note cholshift: XREFcholshift.

 -- : R1 = choldelete (R, J)
     Update a Cholesky factorization given a row or column to delete
     from the original factored matrix.

     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: XREFchol, *note cholupdate: XREFcholupdate,
     *note cholinsert: XREFcholinsert, *note cholshift: XREFcholshift.

 -- : R1 = cholshift (R, I, J)
     Update a Cholesky factorization given a range of columns to shift
     in the original factored matrix.

     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: XREFchol, *note cholupdate: XREFcholupdate,
     *note cholinsert: XREFcholinsert, *note choldelete: XREFcholdelete.

 -- : H = hess (A)
 -- : [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).

     See also: *note eig: XREFeig, *note chol: XREFchol, *note lu:
     XREFlu, *note qr: XREFqr, *note qz: XREFqz, *note schur: XREFschur,
     *note svd: XREFsvd.

 -- : [L, U] = lu (A)
 -- : [L, U, P] = lu (A)
 -- : [L, U, P, Q] = lu (S)
 -- : [L, U, P, Q, R] = lu (S)
 -- : [...] = lu (S, THRESH)
 -- : Y = lu (...)
 -- : [...] = lu (..., "vector")
     Compute the LU decomposition of A.

     If A is full then 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 sparse 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’.  This is the *preferred* way to call ‘lu’ with sparse
     input matrices.

     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 THRESH that defines the pivoting
     threshold can be given.  THRESH can be a scalar, in which case it
     defines the UMFPACK pivoting tolerance for both symmetric and
     unsymmetric cases.  If THRESH 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.

     See also: *note luupdate: XREFluupdate, *note ilu: XREFilu, *note
     chol: XREFchol, *note hess: XREFhess, *note qr: XREFqr, *note qz:
     XREFqz, *note schur: XREFschur, *note svd: XREFsvd.

 -- : [L, U] = luupdate (L, U, X, Y)
 -- : [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: XREFlu, *note cholupdate: XREFcholupdate, *note
     qrupdate: XREFqrupdate.

 -- : [Q, R] = qr (A)
 -- : [Q, R, P] = qr (A)
 -- : X = qr (A) # non-sparse A
 -- : R = qr (A) # sparse A
 -- : X = qr (A, B) # sparse A
 -- : [C, R] = qr (A, B)
 -- : [...] = qr (..., 0)
 -- : [...] = qr (..., "vector")
 -- : [...] = qr (..., "matrix")
     Compute the QR factorization of A, using standard LAPACK
     subroutines.

     The QR factorization is

          Q * R = A

     where Q is an orthogonal matrix and R is upper triangular.

     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

     which multiplied together return the original matrix

          Q * R
            ⇒
               1.0000   2.0000
               3.0000   4.0000

     If just a single return value is requested then it is either R, if
     A is sparse, or X, such that ‘R = triu (X)’ if A is full.  (Note:
     unlike most commands, the single return value is not the first
     return value when multiple values are requested.)

     If a third output P is requested, then ‘qr’ calculates the permuted
     QR factorization

          Q * R = A * P

     where Q is an orthogonal matrix, R is upper triangular, and P is a
     permutation matrix.

     If A is dense, the permuted QR factorization has the additional
     property that the diagonal entries of R are ordered by decreasing
     magnitude.  In other words, ‘abs (diag (R))’ will be ordered from
     largest to smallest.

     If A is sparse, P is a fill-reducing ordering of the columns of A.
     In that case, the diagonal entries of R are not ordered by
     decreasing magnitude.

     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

     If the input matrix A is sparse, the sparse QR factorization is
     computed by using SPQR or CXSPARSE (e.g., if SPQR is not
     available).  Because the matrix Q is, in general, a full matrix, it
     is recommended to request only one return value R.  In that case,
     the computation avoids the construction of Q and returns a sparse R
     such that ‘R = chol (A' * A)’.

     If A is dense, an additional matrix B is supplied and two return
     values are requested, then ‘qr’ returns C, where ‘C = Q' * B’.
     This allows the least squares approximation of ‘A \ B’ to be
     calculated as

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

     If A is a sparse MxN matrix and an additional matrix B is supplied,
     one or two return values are possible.  If one return value X is
     requested and M < N, then X is the minimum 2-norm solution of
     ‘A \ B’.  If M >= N, X is the least squares approximation
     of ‘A \ B’.  If two return values are requested, C and R have the
     same meaning as in the dense case (C is dense and R is sparse).
     The version with one return parameter should be preferred because
     it uses less memory and can handle rank-deficient matrices better.

     If the final argument is the string "vector" then P is a
     permutation vector (of the columns of A) instead of a permutation
     matrix.  In this case, the defining relationship is:

          Q * R = A(:, P)

     The default, however, is to return a permutation matrix and this
     may be explicitly specified by using a final argument of "matrix".

     If the final argument is the scalar 0 an "economy" factorization is
     returned.  If the original matrix A has size MxN and M > N, then
     the "economy" factorization will calculate just N rows in R and N
     columns in Q and omit the zeros in R.  If M ≤ N, there is no
     difference between the economy and standard factorizations.  When
     calculating an "economy" factorization and A is dense, the output P
     is always a vector rather than a matrix.  If A is sparse, output P
     is a sparse permutation matrix.

     Background: 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 permuted QR factorization ‘[Q, R, P] = qr (A)’ allows the
     construction of an orthogonal basis of ‘span (A)’.

     See also: *note chol: XREFchol, *note hess: XREFhess, *note lu:
     XREFlu, *note qz: XREFqz, *note schur: XREFschur, *note svd:
     XREFsvd, *note qrupdate: XREFqrupdate, *note qrinsert:
     XREFqrinsert, *note qrdelete: XREFqrdelete, *note qrshift:
     XREFqrshift.

 -- : [Q1, R1] = qrupdate (Q, R, U, V)
     Update a QR factorization given update vectors or matrices.

     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: XREFqr, *note qrinsert: XREFqrinsert, *note
     qrdelete: XREFqrdelete, *note qrshift: XREFqrshift.

 -- : [Q1, R1] = qrinsert (Q, R, J, X, ORIENT)
     Update a QR factorization given a row or column to insert in the
     original factored matrix.

     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: XREFqr, *note qrupdate: XREFqrupdate, *note
     qrdelete: XREFqrdelete, *note qrshift: XREFqrshift.

 -- : [Q1, R1] = qrdelete (Q, R, J, ORIENT)
     Update a QR factorization given a row or column to delete from the
     original factored matrix.

     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), U, 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 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: XREFqr, *note qrupdate: XREFqrupdate, *note
     qrinsert: XREFqrinsert, *note qrshift: XREFqrshift.

 -- : [Q1, R1] = qrshift (Q, R, I, J)
     Update a QR factorization given a range of columns to shift in the
     original factored matrix.

     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: XREFqr, *note qrupdate: XREFqrupdate, *note
     qrinsert: XREFqrinsert, *note qrdelete: XREFqrdelete.

 -- : LAMBDA = qz (A, B)
 -- : [AA, BB, Q, Z, V, W, LAMBDA] = qz (A, B)
 -- : [AA, BB, Z] = qz (A, B, OPT)
 -- : [AA, BB, Z, LAMBDA] = qz (A, B, OPT)
     Compute the QZ decomposition of a generalized eigenvalue problem.

     The generalized eigenvalue problem is defined as

     A x = LAMBDA B x

     There are three calling forms of the function:

       1. ‘LAMBDA = qz (A, B)’

          Compute the generalized eigenvalues LAMBDA.

       2. ‘[AA, BB, Q, Z, V, W, LAMBDA] = qz (A, B)’

          Compute QZ decomposition, generalized eigenvectors, and
          generalized eigenvalues.


               AA = Q * A * Z, BB = Q * B * Z
               A * V = B * V * diag (LAMBDA)
               W' * A = diag (LAMBDA) * W' * B


          with Q and Z orthogonal (unitary for complex case).

       3. ‘[AA, BB, Z {, LAMBDA}] = qz (A, B, OPT)’

          As in form 2 above, 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
     ‘balance’: XREFbalance.), which may be lead to less accurate
     results than ‘eig’.  The order of output arguments was selected for
     compatibility with MATLAB.

     See also: *note eig: XREFeig, *note gsvd: XREFgsvd, *note balance:
     XREFbalance, *note chol: XREFchol, *note hess: XREFhess, *note lu:
     XREFlu, *note qr: XREFqr, *note qzhess: XREFqzhess, *note schur:
     XREFschur.

 -- : [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 =
               Diagonal Matrix
                 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’.

     See also: *note lu: XREFlu, *note chol: XREFchol, *note hess:
     XREFhess, *note qr: XREFqr, *note qz: XREFqz, *note schur:
     XREFschur, *note svd: XREFsvd.

 -- : S = schur (A)
 -- : S = schur (A, "real")
 -- : S = schur (A, "complex")
 -- : S = schur (A, OPT)
 -- : [U, S] = schur (...)
     Compute the Schur decomposition of A.

     The Schur decomposition is defined as

          S = U' * A * U

     where U is a unitary matrix (‘U'* U’ is identity) and S is upper
     triangular.  The eigenvalues of A (and S) are the diagonal elements
     of S.  If the matrix A is real, then the real Schur decomposition
     is computed, in which the matrix U is orthogonal and S is block
     upper triangular with blocks of size at most ‘2 x 2’ along the
     diagonal.  The diagonal elements of S (or the eigenvalues of the ‘2
     x 2’ blocks, when appropriate) are the eigenvalues of A and S.

     The default for real matrices is a real Schur decomposition.  A
     complex decomposition may be forced by passing the flag "complex".

     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.

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

     See also: *note rsf2csf: XREFrsf2csf, *note ordschur: XREFordschur,
     *note ordeig: XREFordeig, *note lu: XREFlu, *note chol: XREFchol,
     *note hess: XREFhess, *note qr: XREFqr, *note qz: XREFqz, *note
     svd: XREFsvd.

 -- : [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: XREFschur.

 -- : [UR, SR] = ordschur (U, S, SELECT)
     Reorders the real Schur factorization (U,S) obtained with the
     ‘schur’ function, so that selected eigenvalues appear in the upper
     left diagonal blocks of the quasi triangular Schur matrix.

     The logical vector SELECT specifies the selected eigenvalues as
     they appear along S’s diagonal.

     For example, given the matrix ‘A = [1, 2; 3, 4]’, and its Schur
     decomposition

          [U, S] = schur (A)

     which returns

          U =

            -0.82456  -0.56577
             0.56577  -0.82456

          S =

            -0.37228  -1.00000
             0.00000   5.37228


     It is possible to reorder the decomposition so that the positive
     eigenvalue is in the upper left corner, by doing:

          [U, S] = ordschur (U, S, [0,1])

     See also: *note schur: XREFschur, *note ordeig: XREFordeig, *note
     ordqz: XREFordqz.

 -- : [AR, BR, QR, ZR] = ordqz (AA, BB, Q, Z, KEYWORD)
 -- : [AR, BR, QR, ZR] = ordqz (AA, BB, Q, Z, SELECT)
     Reorder the QZ decomposition of a generalized eigenvalue problem.

     The generalized eigenvalue problem is defined as

     A x = LAMBDA B x

     Its generalized Schur decomposition is computed using the ‘qz’
     algorithm:

     ‘[AA, BB, Q, Z] = qz (A, B)’

     where AA, BB, Q, and Z fulfill


          AA = Q * A * Z, BB = Q * B * Z


     The ‘ordqz’ function computes a unitary transformation QR and ZR
     such that the order of the eigenvalue on the diagonal of AA and BB
     is changed.  The resulting reordered matrices AR and BR fulfill:


          AR = QR * A * ZR, BR = QR * B * ZR


     The function can either be called with the KEYWORD argument which
     selects the eigenvalues in the top left block of AR and BR in the
     following way:

     "S", "udi"
          small: leading block has all |LAMBDA| < 1

     "B", "udo"
          big: leading block has all |LAMBDA| ≥ 1

     "-", "lhp"
          negative real part: leading block has all eigenvalues in the
          open left half-plane

     "+", "rhp"
          non-negative real part: leading block has all eigenvalues in
          the closed right half-plane

     If a logical vector SELECT is given instead of a keyword the
     ‘ordqz’ function reorders all eigenvalues ‘k’ to the left block for
     which ‘select(k)’ is true.

     Note: The keywords are compatible with the ones from ‘qr’.

     See also: *note eig: XREFeig, *note ordeig: XREFordeig, *note qz:
     XREFqz, *note schur: XREFschur, *note ordschur: XREFordschur.

 -- : LAMBDA = ordeig (A)
 -- : LAMBDA = ordeig (A, B)
     Return the eigenvalues of quasi-triangular matrices in their order
     of appearance in the matrix A.

     The quasi-triangular matrix A is usually the result of a Schur
     factorization.  If called with a second input B then the
     generalized eigenvalues of the pair A, B are returned in the order
     of appearance of the matrix ‘A-LAMBDA*B’.  The pair A, B is usually
     the result of a QZ decomposition.

     See also: *note ordschur: XREFordschur, *note ordqz: XREFordqz,
     *note eig: XREFeig, *note schur: XREFschur, *note qz: XREFqz.

 -- : ANGLE = subspace (A, B)
     Determine the largest principal angle between two subspaces spanned
     by the columns of matrices A and B.

 -- : S = svd (A)
 -- : [U, S, V] = svd (A)
 -- : [U, S, V] = svd (A, "econ")
 -- : [U, S, V] = svd (A, 0)
     Compute the singular value decomposition of A.

     The singular value decomposition is defined by the relation

          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

     When given a second argument that is not 0, ‘svd’ returns an
     economy-sized decomposition, eliminating the unnecessary rows or
     columns of U or V.

     If the second argument is exactly 0, then the choice of
     decomposition is based on the matrix A.  If A has more rows than
     columns then an economy-sized decomposition is returned, otherwise
     a regular decomposition is calculated.

     Algorithm Notes: When calculating the full decomposition (left and
     right singular matrices in addition to singular values) there is a
     choice of two routines in LAPACK.  The default routine used by
     Octave is ‘gesvd’.  The alternative is ‘gesdd’ which is 5X faster,
     but may use more memory and may be inaccurate for some input
     matrices.  There is a third routine ‘gejsv’, suitable for better
     accuracy at extreme scale.  See the documentation for ‘svd_driver’
     for more information on choosing a driver.

     See also: *note svd_driver: XREFsvd_driver, *note svds: XREFsvds,
     *note eig: XREFeig, *note lu: XREFlu, *note chol: XREFchol, *note
     hess: XREFhess, *note qr: XREFqr, *note qz: XREFqz.

 -- : VAL = svd_driver ()
 -- : OLD_VAL = svd_driver (NEW_VAL)
 -- : svd_driver (NEW_VAL, "local")
     Query or set the underlying LAPACK driver used by ‘svd’.

     Currently recognized values are "gesdd", "gesvd", and "gejsv".  The
     default is "gesvd".

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines it
     calls.  The original variable value is restored when exiting the
     function.

     Algorithm Notes: The LAPACK library routines ‘gesvd’ and ‘gesdd’
     are different only when calculating the full singular value
     decomposition (left and right singular matrices as well as singular
     values).  When calculating just the singular values the following
     discussion is not relevant.

     The newer ‘gesdd’ routine is based on a Divide-and-Conquer
     algorithm that is 5X faster than the alternative ‘gesvd’, which is
     based on QR factorization.  However, the new algorithm can use
     significantly more memory.  For an MxN input matrix the memory
     usage is of order O(min(M,N) ^ 2), whereas the alternative is of
     order O(max(M,N)).

     The routine ‘gejsv’ uses a preconditioned Jacobi SVD algorithm.
     Unlike ‘gesvd’ and ‘gesdd’, in ‘gejsv’, there is no
     bidiagonalization step that could contaminate accuracy in some
     extreme cases.  Also, ‘gejsv’ is known to be optimally accurate in
     some sense.  However, the speed is slower (single threaded at its
     core) and uses more memory (O(min(M,N) ^ 2 + M + N)).

     Beyond speed and memory issues, there have been instances where
     some input matrices were not accurately decomposed by ‘gesdd’.  See
     currently active bug <https://savannah.gnu.org/bugs/?55564>.  Until
     these accuracy issues are resolved in a new version of the LAPACK
     library, the default driver in Octave has been set to "gesvd".

     See also: *note svd: XREFsvd.

 -- : [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(j) < 0,
          (I - beta*housv*housv')x = -norm (x)*e(j) if x(j) >= 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

 -- : [U, H, NU] = krylov (A, V, K, EPS1, PFLG)
     Construct an orthogonal basis U of a block Krylov subspace.

     The block Krylov subspace has the following form:

          [v a*v a^2*v ... a^(k+1)*v]

     The construction is made with 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
==========================

 -- : expm (A)
     Return the exponential of a matrix.

     The matrix exponential is defined as the infinite Taylor series

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

     However, 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 Padé approximation method with three
     step preconditioning (SIAM Journal on Numerical Analysis, 1977).
     Diagonal Padé 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 Padé
     approximation when ‘Dq(A)’ is ill-conditioned.

     See also: *note logm: XREFlogm, *note sqrtm: XREFsqrtm.

 -- : S = logm (A)
 -- : S = logm (A, OPT_ITERS)
 -- : [S, ITERS] = logm (...)
     Compute the matrix logarithm of the square matrix A.

     The implementation utilizes a Padé approximant and the identity

          logm (A) = 2^k * logm (A^(1 / 2^k))

     The optional input 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.

     See also: *note expm: XREFexpm, *note sqrtm: XREFsqrtm.

 -- : S = sqrtm (A)
 -- : [S, 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: XREFexpm, *note logm: XREFlogm.

 -- : kron (A, B)
 -- : kron (A1, A2, ...)
     Form the Kronecker product of two or more matrices.

     This is defined block by block as

          x = [ a(i,j)*b ]

     For example:

          kron (1:4, ones (3, 1))
               ⇒  1  2  3  4
                   1  2  3  4
                   1  2  3  4

     If there are more than two input arguments A1, A2, ..., AN the
     Kronecker product is computed as

          kron (kron (A1, A2), ..., AN)

     Since the Kronecker product is associative, this is well-defined.

 -- : blkmm (A, B)
     Compute products of matrix blocks.

     The blocks are given as 2-dimensional subarrays of the arrays A, B.
     The size of A must have the form ‘[m,k,...]’ and size of B must be
     ‘[k,n,...]’.  The result is then of size ‘[m,n,...]’ and is
     computed as follows:

          for i = 1:prod (size (A)(3:end))
            C(:,:,i) = A(:,:,i) * B(:,:,i)
          endfor

 -- : X = sylvester (A, B, C)
     Solve the Sylvester equation.

     The Sylvester equation is defined as:

          A X + X B = C

     The solution is computed using standard LAPACK subroutines.

     For example:

          sylvester ([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
========================

 -- : X = bicg (A, B)
 -- : X = bicg (A, B, TOL)
 -- : X = bicg (A, B, TOL, MAXIT)
 -- : X = bicg (A, B, TOL, MAXIT, M)
 -- : X = bicg (A, B, TOL, MAXIT, M1, M2)
 -- : X = bicg (A, B, TOL, MAXIT, M, [], X0)
 -- : X = bicg (A, B, TOL, MAXIT, M1, M2, X0)
 -- : X = bicg (A, B, TOL, MAXIT, M, [], X0, ...)
 -- : X = bicg (A, B, TOL, MAXIT, M1, M2, X0, ...)
 -- : [X, FLAG, RELRES, ITER, RESVEC] = bicg (A, B, ...)
     Solve the linear system of equations ‘A * X = B’ by means of the
     Bi-Conjugate Gradient iterative method.

     The input arguments are:

        • A is the matrix of the linear system and it must be square.  A
          can be passed as a matrix, function handle, or inline function
          ‘Afun’ such that ‘Afun (x, "notransp") = A * x’ and
          ‘Afun (x, "transp") = A' * x’.  Additional parameters to
          ‘Afun’ may be passed after X0.

        • B is the right-hand side vector.  It must be a column vector
          with the same number of rows as A.

        • TOL is the required relative tolerance for the residual error,
          ‘B - A * X’.  The iteration stops if
          ‘norm (B - A * X)’ ≤ ‘TOL * norm (B)’.  If TOL is omitted or
          empty, then a tolerance of 1e-6 is used.

        • MAXIT is the maximum allowed number of iterations; if MAXIT is
          omitted or empty then a value of 20 is used.

        • M1, M2 are the preconditioners.  The preconditioner M is given
          as ‘M = M1 * M2’.  Both M1 and M2 can be passed as a matrix or
          as a function handle or inline function ‘g’ such that
          ‘g (X, "notransp") = M1 \ X’ or ‘g (X, "notransp") = M2 \ X’
          and ‘g (X, "transp") = M1' \ X’ or
          ‘g (X, "transp") = M2' \ X’.  If M1 is omitted or empty, then
          preconditioning is not applied.  The preconditioned system is
          theoretically equivalent to applying the ‘bicg’ method to the
          linear system ‘inv (M1) * A * inv (M2) * Y = inv (M1) * B’ and
          ‘inv (M2') * A' * inv (M1') * Z = inv (M2') * B’ and then
          setting ‘X = inv (M2) * Y’.

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

     Any arguments which follow X0 are treated as parameters, and passed
     in an appropriate manner to any of the functions (AFUN or MFUN) or
     that have been given to ‘bicg’.

     The output parameters are:

        • X is the computed approximation to the solution of
          ‘A * X = B’.  If the algorithm did not converge, then X is the
          iteration which has the minimum residual.

        • FLAG indicates the exit status:

             • 0: The algorithm converged to within the prescribed
               tolerance.

             • 1: The algorithm did not converge and it reached the
               maximum number of iterations.

             • 2: The preconditioner matrix is singular.

             • 3: The algorithm stagnated, i.e., the absolute value of
               the difference between the current iteration X and the
               previous is less than ‘eps * norm (X,2)’.

             • 4: The algorithm could not continue because intermediate
               values became too small or too large for reliable
               computation.

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

        • ITER is the iteration which X is computed.

        • RESVEC is a vector containing the residual at each iteration.
          The total number of iterations performed is given by ‘length
          (RESVEC) - 1’.

     Consider a trivial problem with a tridiagonal matrix

          n = 20;
          A = toeplitz (sparse ([1, 1], [1, 2], [2, 1] * n ^ 2, 1, n)) + ...
              toeplitz (sparse (1, 2, -1, 1, n) * n / 2, ...
                        sparse (1, 2, 1, 1, n) * n / 2);
          b = A * ones (n, 1);
          restart = 5;
          [M1, M2] = ilu (A);  # in this tridiag case, it corresponds to lu (A)
          M = M1 * M2;
          Afun = @(x, string) strcmp (string, "notransp") * (A * x) + ...
                               strcmp (string, "transp") * (A' * x);
          Mfun = @(x, string) strcmp (string, "notransp") * (M \ x) + ...
                               strcmp (string, "transp") * (M' \ x);
          M1fun = @(x, string) strcmp (string, "notransp") * (M1 \ x) + ...
                               strcmp (string, "transp") * (M1' \ x);
          M2fun = @(x, string) strcmp (string, "notransp") * (M2 \ x) + ...
                               strcmp (string, "transp") * (M2' \ x);

     EXAMPLE 1: simplest usage of ‘bicg’

          x = bicg (A, b)

     EXAMPLE 2: ‘bicg’ with a function that computes ‘A*X’ and ‘A'*X’

          x = bicg (Afun, b, [], n)

     EXAMPLE 3: ‘bicg’ with a preconditioner matrix M

          x = bicg (A, b, 1e-6, n, M)

     EXAMPLE 4: ‘bicg’ with a function as preconditioner

          x = bicg (Afun, b, 1e-6, n, Mfun)

     EXAMPLE 5: ‘bicg’ with preconditioner matrices M1 and M2

          x = bicg (A, b, 1e-6, n, M1, M2)

     EXAMPLE 6: ‘bicg’ with functions as preconditioners

          x = bicg (Afun, b, 1e-6, n, M1fun, M2fun)

     EXAMPLE 7: ‘bicg’ with as input a function requiring an argument

          function y = Ap (A, x, string, z)
            ## compute A^z * x or (A^z)' * x
            y = x;
            if (strcmp (string, "notransp"))
              for i = 1:z
                y = A * y;
              endfor
            elseif (strcmp (string, "transp"))
              for i = 1:z
                y = A' * y;
              endfor
            endif
          endfunction

          Apfun = @(x, string, p) Ap (A, x, string, p);
          x = bicg (Apfun, b, [], [], [], [], [], 2);

     Reference:

     Y. Saad, ‘Iterative Methods for Sparse Linear Systems’, Second
     edition, 2003, SIAM.

     See also: *note bicgstab: XREFbicgstab, *note cgs: XREFcgs, *note
     gmres: XREFgmres, *note pcg: XREFpcg, *note qmr: XREFqmr, *note
     tfqmr: XREFtfqmr.

 -- : X = bicgstab (A, B, TOL, MAXIT, M1, M2, X0, ...)
 -- : X = bicgstab (A, B, TOL, MAXIT, M, [], X0, ...)
 -- : [X, FLAG, RELRES, ITER, RESVEC] = bicgstab (A, B, ...)
     Solve ‘A x = b’ using the stabilized Bi-conjugate gradient
     iterative method.

     The input parameters are:

        − A is the matrix of the linear system and it must be square.  A
          can be passed as a matrix, function handle, or inline function
          ‘Afun’ such that ‘Afun(x) = A * x’.  Additional parameters to
          ‘Afun’ are passed after X0.

        − B is the right hand side vector.  It must be a column vector
          with the same number of rows as A.

        − TOL is the required relative tolerance for the residual error,
          ‘B - A * X’.  The iteration stops if
          ‘norm (B - A * X)’ ≤ ‘TOL * norm (B)’.  If TOL is omitted or
          empty, then a tolerance of 1e-6 is used.

        − MAXIT the maximum number of outer iterations, if not given or
          set to [] the default value ‘min (20, numel (b))’ is used.

        − M1, M2 are the preconditioners.  The preconditioner M is given
          as ‘M = M1 * M2’.  Both M1 and M2 can be passed as a matrix or
          as a function handle or inline function ‘g’ such that ‘g(X) =
          M1 \ X’ or ‘g(X) = M2 \ X’.  The technique used is the right
          preconditioning, i.e., it is solved ‘A * inv (M) * Y = B’ and
          then ‘X = inv (M) * Y’.

        − X0 the initial guess, if not given or set to [] the default
          value ‘zeros (size (B))’ is used.

     The arguments which follow X0 are treated as parameters, and passed
     in a proper way to any of the functions (A or M) which are passed
     to ‘bicstab’.

     The output parameters are:

        − X is the approximation computed.  If the method doesn’t
          converge then it is the iterated with the minimum residual.

        − FLAG indicates the exit status:

             − 0: iteration converged to the within the chosen tolerance

             − 1: the maximum number of iterations was reached before
               convergence

             − 2: the preconditioner matrix is singular

             − 3: the algorithm reached stagnation

             − 4: the algorithm can’t continue due to a division by zero

        − RELRES is the relative residual obtained with as ‘(A*X-B) /
          norm(B)’.

        − ITER is the (possibly half) iteration which X is computed.  If
          it is an half iteration then it is ‘ITER + 0.5’

        − RESVEC is a vector containing the residual of each half and
          total iteration (There are also the half iterations since X is
          computed in two steps at each iteration).  Doing
          ‘(length(RESVEC) - 1) / 2’ is possible to see the total number
          of (total) iterations performed.

     Let us consider a trivial problem with a tridiagonal matrix

          n = 20;
          A = toeplitz (sparse ([1, 1], [1, 2], [2, 1] * n ^ 2, 1, n))  + ...
              toeplitz (sparse (1, 2, -1, 1, n) * n / 2, ...
              sparse (1, 2, 1, 1, n) * n / 2);
          b = A * ones (n, 1);
          restart = 5;
          [M1, M2] = ilu (A); # in this tridiag case, it corresponds to lu (A)
          M = M1 * M2;
          Afun = @(x) A * x;
          Mfun = @(x) M \ x;
          M1fun = @(x) M1 \ x;
          M2fun = @(x) M2 \ x;

     EXAMPLE 1: simplest usage of ‘bicgstab’

          x = bicgstab (A, b, [], n)

     EXAMPLE 2: ‘bicgstab’ with a function which computes ‘A * X’

          x = bicgstab (Afun, b, [], n)

     EXAMPLE 3: ‘bicgstab’ with a preconditioner matrix M

          x = bicgstab (A, b, [], 1e-06, n, M)

     EXAMPLE 4: ‘bicgstab’ with a function as preconditioner

          x = bicgstab (Afun, b, 1e-6, n, Mfun)

     EXAMPLE 5: ‘bicgstab’ with preconditioner matrices M1 and M2

          x = bicgstab (A, b, [], 1e-6, n, M1, M2)

     EXAMPLE 6: ‘bicgstab’ with functions as preconditioners

          x = bicgstab (Afun, b, 1e-6, n, M1fun, M2fun)

     EXAMPLE 7: ‘bicgstab’ with as input a function requiring an
     argument

          function y = Ap (A, x, z) # compute A^z * x
             y = x;
             for i = 1:z
               y = A * y;
             endfor
           endfunction
          Apfun = @(x, string, p) Ap (A, x, string, p);
          x = bicgstab (Apfun, b, [], [], [], [], [], 2);

     EXAMPLE 8: explicit example to show that ‘bicgstab’ uses a right
     preconditioner

          [M1, M2] = ilu (A + 0.1 * eye (n)); # factorization of A perturbed
          M = M1 * M2;

          ## reference solution computed by bicgstab after one iteration
          [x_ref, fl] = bicgstab (A, b, [], 1, M)

          ## right preconditioning
          [y, fl] = bicgstab (A / M, b, [], 1)
          x = M \ y # compare x and x_ref


     Reference:

     Y. Saad, ‘Iterative Methods for Sparse Linear Systems’, Second
     edition, 2003, SIAM

     See also: *note bicg: XREFbicg, *note cgs: XREFcgs, *note gmres:
     XREFgmres, *note pcg: XREFpcg, *note qmr: XREFqmr, *note tfqmr:
     XREFtfqmr.

 -- : X = cgs (A, B, TOL, MAXIT, M1, M2, X0, ...)
 -- : X = cgs (A, B, TOL, MAXIT, M, [], X0, ...)
 -- : [X, FLAG, RELRES, ITER, RESVEC] = cgs (A, B, ...)
     Solve ‘A x = b’, where A is a square matrix, using the Conjugate
     Gradients Squared method.

     The input arguments are:

        − A is the matrix of the linear system and it must be square.  A
          can be passed as a matrix, function handle, or inline function
          ‘Afun’ such that ‘Afun(x) = A * x’.  Additional parameters to
          ‘Afun’ are passed after X0.

        − B is the right hand side vector.  It must be a column vector
          with same number of rows of A.

        − TOL is the relative tolerance, if not given or set to [] the
          default value 1e-6 is used.

        − MAXIT the maximum number of outer iterations, if not given or
          set to [] the default value ‘min (20, numel (b))’ is used.

        − M1, M2 are the preconditioners.  The preconditioner matrix is
          given as ‘M = M1 * M2’.  Both M1 and M2 can be passed as a
          matrix or as a function handle or inline function ‘g’ such
          that ‘g(x) = M1 \ x’ or ‘g(x) = M2 \ x’.  If M1 is empty or
          not passed then no preconditioners are applied.  The technique
          used is the right preconditioning, i.e., it is solved
          ‘A*inv(M)*y = b’ and then ‘X = inv(M)*y’.

        − X0 the initial guess, if not given or set to [] the default
          value ‘zeros (size (b))’ is used.

     The arguments which follow X0 are treated as parameters, and passed
     in a proper way to any of the functions (A or P) which are passed
     to ‘cgs’.

     The output parameters are:

        − X is the approximation computed.  If the method doesn’t
          converge then it is the iterated with the minimum residual.

        − FLAG indicates the exit status:

             − 0: iteration converged to the within the chosen tolerance

             − 1: the maximum number of iterations was reached before
               convergence

             − 2: the preconditioner matrix is singular

             − 3: the algorithm reached stagnation

             − 4: the algorithm can’t continue due to a division by zero

        − RELRES is the relative residual obtained with as ‘(A*X-B) /
          norm(B)’.

        − ITER is the iteration which X is computed.

        − RESVEC is a vector containing the residual at each iteration.
          Doing ‘length(RESVEC) - 1’ is possible to see the total number
          of iterations performed.

     Let us consider a trivial problem with a tridiagonal matrix

          n = 20;
          A = toeplitz (sparse ([1, 1], [1, 2], [2, 1] * n ^ 2, 1, n))  + ...
              toeplitz (sparse (1, 2, -1, 1, n) * n / 2, ...
              sparse (1, 2, 1, 1, n) * n / 2);
          b = A * ones (n, 1);
          restart = 5;
          [M1, M2] = ilu (A); # in this tridiag case it corresponds to chol (A)'
          M = M1 * M2;
          Afun = @(x) A * x;
          Mfun = @(x) M \ x;
          M1fun = @(x) M1 \ x;
          M2fun = @(x) M2 \ x;

     EXAMPLE 1: simplest usage of ‘cgs’

          x = cgs (A, b, [], n)

     EXAMPLE 2: ‘cgs’ with a function which computes ‘A * X’

          x = cgs (Afun, b, [], n)

     EXAMPLE 3: ‘cgs’ with a preconditioner matrix M

          x = cgs (A, b, [], 1e-06, n, M)

     EXAMPLE 4: ‘cgs’ with a function as preconditioner

          x = cgs (Afun, b, 1e-6, n, Mfun)

     EXAMPLE 5: ‘cgs’ with preconditioner matrices M1 and M2

          x = cgs (A, b, [], 1e-6, n, M1, M2)

     EXAMPLE 6: ‘cgs’ with functions as preconditioners

          x = cgs (Afun, b, 1e-6, n, M1fun, M2fun)

     EXAMPLE 7: ‘cgs’ with as input a function requiring an argument

          function y = Ap (A, x, z) # compute A^z * x
             y = x;
             for i = 1:z
               y = A * y;
             endfor
           endfunction
          Apfun = @(x, string, p) Ap (A, x, string, p);
          x = cgs (Apfun, b, [], [], [], [], [], 2);

     EXAMPLE 8: explicit example to show that ‘cgs’ uses a right
     preconditioner

          [M1, M2] = ilu (A + 0.3 * eye (n)); # factorization of A perturbed
          M = M1 * M2;

          ## reference solution computed by cgs after one iteration
          [x_ref, fl] = cgs (A, b, [], 1, M)

          ## right preconditioning
          [y, fl] = cgs (A / M, b, [], 1)
          x = M \ y # compare x and x_ref


     References:

     Y. Saad, ‘Iterative Methods for Sparse Linear Systems’, Second
     edition, 2003, SIAM

     See also: *note pcg: XREFpcg, *note bicgstab: XREFbicgstab, *note
     bicg: XREFbicg, *note gmres: XREFgmres, *note qmr: XREFqmr, *note
     tfqmr: XREFtfqmr.

 -- : X = gmres (A, B, RESTART, TOL, MAXIT, M1, M2, X0, ...)
 -- : X = gmres (A, B, RESTART, TOL, MAXIT, M, [], X0, ...)
 -- : [X, FLAG, RELRES, ITER, RESVEC] = gmres (A, B, ...)
     Solve ‘A x = b’ using the Preconditioned GMRES iterative method
     with restart, a.k.a.  PGMRES(restart).

     The input arguments are:

        − A is the matrix of the linear system and it must be square.  A
          can be passed as a matrix, function handle, or inline function
          ‘Afun’ such that ‘Afun(x) = A * x’.  Additional parameters to
          ‘Afun’ are passed after X0.

        − B is the right hand side vector.  It must be a column vector
          with the same numbers of rows as A.

        − RESTART is the number of iterations before that the method
          restarts.  If it is [] or N = numel (b), then the restart is
          not applied.

        − TOL is the required relative tolerance for the preconditioned
          residual error, ‘inv (M) * (B - A * X)’.  The iteration stops
          if ‘norm (inv (M) * (B - A * X)) ≤ TOL * norm (inv (M) * B)’.
          If TOL is omitted or empty, then a tolerance of 1e-6 is used.

        − MAXIT is the maximum number of outer iterations, if not given
          or set to [], then the default value ‘min (10, N / RESTART)’
          is used.  Note that, if RESTART is empty, then MAXIT is the
          maximum number of iterations.  If RESTART and MAXIT are not
          empty, then the maximum number of iterations is ‘RESTART *
          MAXIT’.  If both RESTART and MAXIT are empty, then the maximum
          number of iterations is set to ‘min (10, N)’.

        − M1, M2 are the preconditioners.  The preconditioner M is given
          as ‘M = M1 * M2’.  Both M1 and M2 can be passed as a matrix,
          function handle, or inline function ‘g’ such that ‘g(x) = M1 \
          x’ or ‘g(x) = M2 \ x’.  If M1 is [] or not given, then the
          preconditioner is not applied.  The technique used is the
          left-preconditioning, i.e., it is solved ‘inv(M) * A * X =
          inv(M) * B’ instead of ‘A * X = B’.

        − X0 is the initial guess, if not given or set to [], then the
          default value ‘zeros (size (B))’ is used.

     The arguments which follow X0 are treated as parameters, and passed
     in a proper way to any of the functions (A or M or M1 or M2) which
     are passed to ‘gmres’.

     The outputs are:

        − X the computed approximation.  If the method does not
          converge, then it is the iterated with minimum residual.

        − FLAG indicates the exit status:

          0 : iteration converged to within the specified tolerance

          1 : maximum number of iterations exceeded

          2 : the preconditioner matrix is singular

          3 : algorithm reached stagnation (the relative difference between two
               consecutive iterations is less than eps)

        − RELRES is the value of the relative preconditioned residual of
          the approximation X.

        − ITER is a vector containing the number of outer iterations and
          inner iterations performed to compute X.  That is:

             • ITER(1): number of outer iterations, i.e., how many times
               the method restarted.  (if RESTART is empty or N, then it
               is 1, if not 1 ≤ ITER(1) ≤ MAXIT).

             • ITER(2): the number of iterations performed before the
               restart, i.e., the method restarts when ‘ITER(2) =
               RESTART’.  If RESTART is empty or N, then 1 ≤ ITER(2) ≤
               MAXIT.

          To be more clear, the approximation X is computed at the
          iteration ‘(ITER(1) - 1) * RESTART + ITER(2)’.  Since the
          output X corresponds to the minimal preconditioned residual
          solution, the total number of iterations that the method
          performed is given by ‘length (resvec) - 1’.

        − RESVEC is a vector containing the preconditioned relative
          residual at each iteration, including the 0-th iteration ‘norm
          (A * X0 - B)’.

     Let us consider a trivial problem with a tridiagonal matrix

          n = 20;
          A = toeplitz (sparse ([1, 1], [1, 2], [2, 1] * n ^ 2, 1, n))  + ...
              toeplitz (sparse (1, 2, -1, 1, n) * n / 2, ...
              sparse (1, 2, 1, 1, n) * n / 2);
          b = A * ones (n, 1);
          restart = 5;
          [M1, M2] = ilu (A); # in this tridiag case, it corresponds to lu (A)
          M = M1 * M2;
          Afun = @(x) A * x;
          Mfun = @(x) M \ x;
          M1fun = @(x) M1 \ x;
          M2fun = @(x) M2 \ x;

     EXAMPLE 1: simplest usage of ‘gmres’

          x = gmres (A, b, [], [], n)

     EXAMPLE 2: ‘gmres’ with a function which computes ‘A * X’

          x = gmres (Afun, b, [], [], n)

     EXAMPLE 3: usage of ‘gmres’ with the restart

          x = gmres (A, b, restart);

     EXAMPLE 4: ‘gmres’ with a preconditioner matrix M with and without
     restart

          x = gmres (A, b, [], 1e-06, n, M)
          x = gmres (A, b, restart, 1e-06, n, M)

     EXAMPLE 5: ‘gmres’ with a function as preconditioner

          x = gmres (Afun, b, [], 1e-6, n, Mfun)

     EXAMPLE 6: ‘gmres’ with preconditioner matrices M1 and M2

          x = gmres (A, b, [], 1e-6, n, M1, M2)

     EXAMPLE 7: ‘gmres’ with functions as preconditioners

          x = gmres (Afun, b, 1e-6, n, M1fun, M2fun)

     EXAMPLE 8: ‘gmres’ with as input a function requiring an argument

            function y = Ap (A, x, p) # compute A^p * x
               y = x;
               for i = 1:p
                 y = A * y;
               endfor
            endfunction
          Apfun = @(x, p) Ap (A, x, p);
          x = gmres (Apfun, b, [], [], [], [], [], [], 2);

     EXAMPLE 9: explicit example to show that ‘gmres’ uses a left
     preconditioner

          [M1, M2] = ilu (A + 0.1 * eye (n)); # factorization of A perturbed
          M = M1 * M2;

          ## reference solution computed by gmres after two iterations
          [x_ref, fl] = gmres (A, b, [], [], 1, M)

          ## left preconditioning
          [x, fl] = gmres (M \ A, M \ b, [], [], 1)
          x # compare x and x_ref


     Reference:

     Y. Saad, ‘Iterative Methods for Sparse Linear Systems’, Second
     edition, 2003, SIAM

     See also: *note bicg: XREFbicg, *note bicgstab: XREFbicgstab, *note
     cgs: XREFcgs, *note pcg: XREFpcg, *note pcr: XREFpcr, *note qmr:
     XREFqmr, *note tfqmr: XREFtfqmr.

 -- : X = qmr (A, B, RTOL, MAXIT, M1, M2, X0)
 -- : X = qmr (A, B, RTOL, MAXIT, P)
 -- : [X, FLAG, RELRES, ITER, RESVEC] = qmr (A, B, ...)
     Solve ‘A x = b’ using the Quasi-Minimal Residual iterative method
     (without look-ahead).

        − RTOL is the relative tolerance, if not given or set to [] the
          default value 1e-6 is used.

        − MAXIT the maximum number of outer iterations, if not given or
          set to [] the default value ‘min (20, numel (b))’ is used.

        − X0 the initial guess, if not given or set to [] the default
          value ‘zeros (size (b))’ is used.

     A can be passed as a matrix or as a function handle or inline
     function ‘f’ such that ‘f(x, "notransp") = A*x’ and ‘f(x, "transp")
     = A'*x’.

     The preconditioner P is given as ‘P = M1 * M2’.  Both M1 and M2 can
     be passed as a matrix or as a function handle or inline function
     ‘g’ such that ‘g(x, "notransp") = M1 \ x’ or ‘g(x, "notransp") = M2
     \ x’ and ‘g(x, "transp") = M1' \ x’ or ‘g(x, "transp") = M2' \ x’.

     If called with more than one output parameter

        − FLAG indicates the exit status:

             − 0: iteration converged to the within the chosen tolerance

             − 1: the maximum number of iterations was reached before
               convergence

             − 3: the algorithm reached stagnation

          (the value 2 is unused but skipped for compatibility).

        − RELRES is the final value of the relative residual.

        − ITER is the number of iterations performed.

        − RESVEC is a vector containing the residual norms at each
          iteration.

     References:

       1. R. Freund and N. Nachtigal, ‘QMR: a quasi-minimal residual
          method for non-Hermitian linear systems’, Numerische
          Mathematik, 1991, 60, pp. 315–339.

       2. R. Barrett, M. Berry, T. Chan, J. Demmel, J. Donato, J.
          Dongarra, V. Eijkhour, R. Pozo, C. Romine, and H. van der
          Vorst, ‘Templates for the solution of linear systems: Building
          blocks for iterative methods’, SIAM, 2nd ed., 1994.

     See also: *note bicg: XREFbicg, *note bicgstab: XREFbicgstab, *note
     cgs: XREFcgs, *note gmres: XREFgmres, *note pcg: XREFpcg.

 -- : X = tfqmr (A, B, TOL, MAXIT, M1, M2, X0, ...)
 -- : X = tfqmr (A, B, TOL, MAXIT, M, [], X0, ...)
 -- : [X, FLAG, RELRES, ITER, RESVEC] = tfqmr (A, B, ...)
     Solve ‘A x = b’ using the Transpose-Tree qmr method, based on the
     cgs.

     The input parameters are:

        − A is the matrix of the linear system and it must be square.  A
          can be passed as a matrix, function handle, or inline function
          ‘Afun’ such that ‘Afun(x) = A * x’.  Additional parameters to
          ‘Afun’ are passed after X0.

        − B is the right hand side vector.  It must be a column vector
          with the same number of rows as A.

        − TOL is the relative tolerance, if not given or set to [] the
          default value 1e-6 is used.

        − MAXIT the maximum number of outer iterations, if not given or
          set to [] the default value ‘min (20, numel (b))’ is used.  To
          be compatible, since the method as different behaviors in the
          iteration number is odd or even, is considered as iteration in
          ‘tfqmr’ the entire odd-even cycle.  That is, to make an entire
          iteration, the algorithm performs two sub-iterations: the odd
          one and the even one.

        − M1, M2 are the preconditioners.  The preconditioner M is given
          as ‘M = M1 * M2’.  Both M1 and M2 can be passed as a matrix or
          as a function handle or inline function ‘g’ such that ‘g(x) =
          M1 \ x’ or ‘g(x) = M2 \ x’.  The technique used is the
          right-preconditioning, i.e., it is solved ‘A*inv(M)*y = b’ and
          then ‘x = inv(M)*y’, instead of ‘A x = b’.

        − X0 the initial guess, if not given or set to [] the default
          value ‘zeros (size (b))’ is used.

     The arguments which follow X0 are treated as parameters, and passed
     in a proper way to any of the functions (A or M) which are passed
     to ‘tfqmr’.

     The output parameters are:

        − X is the approximation computed.  If the method doesn’t
          converge then it is the iterated with the minimum residual.

        − FLAG indicates the exit status:

             − 0: iteration converged to the within the chosen tolerance

             − 1: the maximum number of iterations was reached before
               convergence

             − 2: the preconditioner matrix is singular

             − 3: the algorithm reached stagnation

             − 4: the algorithm can’t continue due to a division by zero

        − RELRES is the relative residual obtained as ‘(A*X-B) / norm
          (B)’.

        − ITER is the iteration which X is computed.

        − RESVEC is a vector containing the residual at each iteration
          (including ‘norm (b - A x0)’).  Doing ‘length (RESVEC) - 1’ is
          possible to see the total number of iterations performed.

     Let us consider a trivial problem with a tridiagonal matrix

          n = 20;
          A = toeplitz (sparse ([1, 1], [1, 2], [2, 1] * n ^ 2, 1, n))  + ...
              toeplitz (sparse (1, 2, -1, 1, n) * n / 2, ...
              sparse (1, 2, 1, 1, n) * n / 2);
          b = A * ones (n, 1);
          restart = 5;
          [M1, M2] = ilu (A); # in this tridiag case it corresponds to chol (A)'
          M = M1 * M2;
          Afun = @(x) A * x;
          Mfun = @(x) M \ x;
          M1fun = @(x) M1 \ x;
          M2fun = @(x) M2 \ x;

     EXAMPLE 1: simplest usage of ‘tfqmr’

          x = tfqmr (A, b, [], n)

     EXAMPLE 2: ‘tfqmr’ with a function which computes ‘A * X’

          x = tfqmr (Afun, b, [], n)

     EXAMPLE 3: ‘tfqmr’ with a preconditioner matrix M

          x = tfqmr (A, b, [], 1e-06, n, M)

     EXAMPLE 4: ‘tfqmr’ with a function as preconditioner

          x = tfqmr (Afun, b, 1e-6, n, Mfun)

     EXAMPLE 5: ‘tfqmr’ with preconditioner matrices M1 and M2

          x = tfqmr (A, b, [], 1e-6, n, M1, M2)

     EXAMPLE 6: ‘tfmqr’ with functions as preconditioners

          x = tfqmr (Afun, b, 1e-6, n, M1fun, M2fun)

     EXAMPLE 7: ‘tfqmr’ with as input a function requiring an argument

          function y = Ap (A, x, z) # compute A^z * x
             y = x;
             for i = 1:z
               y = A * y;
             endfor
           endfunction
          Apfun = @(x, string, p) Ap (A, x, string, p);
          x = tfqmr (Apfun, b, [], [], [], [], [], 2);

     EXAMPLE 8: explicit example to show that ‘tfqmr’ uses a right
     preconditioner

          [M1, M2] = ilu (A + 0.3 * eye (n)); # factorization of A perturbed
          M = M1 * M2;

          ## reference solution computed by tfqmr after one iteration
          [x_ref, fl] = tfqmr (A, b, [], 1, M)

          ## right preconditioning
          [y, fl] = tfqmr (A / M, b, [], 1)
          x = M \ y # compare x and x_ref


     Reference:

     Y. Saad, ‘Iterative Methods for Sparse Linear Systems’, Second
     edition, 2003, SIAM

     See also: *note bicg: XREFbicg, *note bicgstab: XREFbicgstab, *note
     cgs: XREFcgs, *note gmres: XREFgmres, *note pcg: XREFpcg, *note
     qmr: XREFqmr, *note pcr: XREFpcr.


File: octave.info,  Node: Vectorization and Faster Code Execution,  Next: Nonlinear Equations,  Prev: Linear Algebra,  Up: Top

19 Vectorization and Faster Code Execution
******************************************

Vectorization is a programming technique that uses vector operations
instead of element-by-element loop-based operations.  Besides frequently
producing more succinct Octave code, vectorization also allows for
better optimization in the subsequent implementation.  The optimizations
may occur either in Octave’s own Fortran, C, or C++ internal
implementation, or even at a lower level depending on the compiler and
external numerical libraries used to build Octave.  The ultimate goal is
to make use of your hardware’s vector instructions if possible or to
perform other optimizations in software.

   Vectorization is not a concept unique to Octave, but it is
particularly important because Octave is a matrix-oriented language.
Vectorized Octave code will see a dramatic speed up (10X–100X) in most
cases.

   This chapter discusses vectorization and other techniques for writing
faster code.

* Menu:

* Basic Vectorization::        Basic techniques for code optimization
* Broadcasting::               Broadcasting operations
* Function Application::       Applying functions to arrays, cells, and structs
* Accumulation::               Accumulation functions
* Miscellaneous Techniques::   Other techniques for speeding up code
* Examples::


File: octave.info,  Node: Basic Vectorization,  Next: Broadcasting,  Up: Vectorization and Faster Code Execution

19.1 Basic Vectorization
========================

To a very good first approximation, the goal in vectorization is to
write code that avoids loops and uses whole-array operations.  As a
trivial example, consider

     for i = 1:n
       for j = 1:m
         c(i,j) = a(i,j) + b(i,j);
       endfor
     endfor

compared to the much simpler

     c = a + b;

This isn’t merely easier to write; it is also internally much easier to
optimize.  Octave delegates this operation to an underlying
implementation which, among other optimizations, may use special vector
hardware instructions or could conceivably even perform the additions in
parallel.  In general, if the code is vectorized, the underlying
implementation has more freedom about the assumptions it can make in
order to achieve faster execution.

   This is especially important for loops with "cheap" bodies.  Often it
suffices to vectorize just the innermost loop to get acceptable
performance.  A general rule of thumb is that the "order" of the
vectorized body should be greater or equal to the "order" of the
enclosing loop.

   As a less trivial example, instead of

     for i = 1:n-1
       a(i) = b(i+1) - b(i);
     endfor

write

     a = b(2:n) - b(1:n-1);

   This shows an important general concept about using arrays for
indexing instead of looping over an index variable.  *Note Index
Expressions::.  Also use boolean indexing generously.  If a condition
needs to be tested, this condition can also be written as a boolean
index.  For instance, instead of

     for i = 1:n
       if (a(i) > 5)
         a(i) -= 20
       endif
     endfor

write

     a(a>5) -= 20;

which exploits the fact that ‘a > 5’ produces a boolean index.

   Use elementwise vector operators whenever possible to avoid looping
(operators like ‘.*’ and ‘.^’).  *Note Arithmetic Ops::.

   Also exploit broadcasting in these elementwise operators both to
avoid looping and unnecessary intermediate memory allocations.  *Note
Broadcasting::.

   Use built-in and library functions if possible.  Built-in and
compiled functions are very fast.  Even with an m-file library function,
chances are good that it is already optimized, or will be optimized more
in a future release.

   For instance, even better than

     a = b(2:n) - b(1:n-1);

is

     a = diff (b);

   Most Octave functions are written with vector and array arguments in
mind.  If you find yourself writing a loop with a very simple operation,
chances are that such a function already exists.  The following
functions occur frequently in vectorized code:

   • Index manipulation

        • find

        • sub2ind

        • ind2sub

        • sort

        • unique

        • lookup

        • ifelse / merge

   • Repetition

        • repmat

        • repelems

   • Vectorized arithmetic

        • sum

        • prod

        • cumsum

        • cumprod

        • sumsq

        • diff

        • dot

        • cummax

        • cummin

   • Shape of higher dimensional arrays

        • reshape

        • resize

        • permute

        • squeeze

        • deal


File: octave.info,  Node: Broadcasting,  Next: Function Application,  Prev: Basic Vectorization,  Up: Vectorization and Faster Code Execution

19.2 Broadcasting
=================

Broadcasting refers to how Octave binary operators and functions behave
when their matrix or array operands or arguments differ in size.  Since
version 3.6.0, Octave now automatically broadcasts vectors, matrices,
and arrays when using elementwise binary operators and functions.
Broadly speaking, smaller arrays are “broadcast” across the larger one,
until they have a compatible shape.  The rule is that corresponding
array dimensions must either

  1. be equal, or

  2. one of them must be 1.

In case all dimensions are equal, no broadcasting occurs and ordinary
element-by-element arithmetic takes place.  For arrays of higher
dimensions, if the number of dimensions isn’t the same, then missing
trailing dimensions are treated as 1.  When one of the dimensions is 1,
the array with that singleton dimension gets copied along that dimension
until it matches the dimension of the other array.  For example,
consider

     x = [1 2 3;
          4 5 6;
          7 8 9];

     y = [10 20 30];

     x + y

Without broadcasting, ‘x + y’ would be an error because the dimensions
do not agree.  However, with broadcasting it is as if the following
operation were performed:

     x = [1 2 3
          4 5 6
          7 8 9];

     y = [10 20 30
          10 20 30
          10 20 30];

     x + y
     ⇒    11   22   33
           14   25   36
           17   28   39

That is, the smaller array of size ‘[1 3]’ gets copied along the
singleton dimension (the number of rows) until it is ‘[3 3]’.  No actual
copying takes place, however.  The internal implementation reuses
elements along the necessary dimension in order to achieve the desired
effect without copying in memory.

   Both arrays can be broadcast across each other, for example, all
pairwise differences of the elements of a vector with itself:

     y - y'
     ⇒    0   10   20
         -10    0   10
         -20  -10    0

Here the vectors of size ‘[1 3]’ and ‘[3 1]’ both get broadcast into
matrices of size ‘[3 3]’ before ordinary matrix subtraction takes place.

   A special case of broadcasting that may be familiar is when all
dimensions of the array being broadcast are 1, i.e., the array is a
scalar.  Thus for example, operations like ‘x - 42’ and ‘max (x, 2)’ are
basic examples of broadcasting.

   For a higher-dimensional example, suppose ‘img’ is an RGB image of
size ‘[m n 3]’ and we wish to multiply each color by a different scalar.
The following code accomplishes this with broadcasting,

     img .*= permute ([0.8, 0.9, 1.2], [1, 3, 2]);

Note the usage of permute to match the dimensions of the ‘[0.8, 0.9,
1.2]’ vector with ‘img’.

   For functions that are not written with broadcasting semantics,
‘bsxfun’ can be useful for coercing them to broadcast.

 -- : bsxfun (F, A, B)
     Apply a binary function F element-by-element to two array arguments
     A and B, expanding singleton dimensions in either input argument as
     necessary.

     F is a function handle, inline function, or string containing the
     name of the function to evaluate.  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 arrays will be expanded to the same
     dimensionality as the other array.

     See also: *note arrayfun: XREFarrayfun, *note cellfun: XREFcellfun.

   Broadcasting is only applied if either of the two broadcasting
conditions hold.  As usual, however, broadcasting does not apply when
two dimensions differ and neither is 1:

     x = [1 2 3
          4 5 6];
     y = [10 20
          30 40];
     x + y

This will produce an error about nonconformant arguments.

   Besides common arithmetic operations, several functions of two
arguments also broadcast.  The full list of functions and operators that
broadcast is

           plus      +
           minus     -
           times     .*
           rdivide   ./
           ldivide   .\
           power     .^
           lt        <
           le        <=
           eq        ==
           gt        >
           ge        >=
           ne        !=  ~=
           and       &
           or        |
           atan2
           hypot
           max
           min
           mod
           rem
           xor

           +=  -=  .*=  ./=  .\=  .^=  &=  |=

   Here is a real example of the power of broadcasting.  The
Floyd-Warshall algorithm is used to calculate the shortest path lengths
between every pair of vertices in a graph.  A naive implementation for a
graph adjacency matrix of order N might look like this:

     for k = 1:n
       for i = 1:n
         for j = 1:n
           dist(i,j) = min (dist(i,j), dist(i,k) + dist(k,j));
         endfor
       endfor
     endfor

   Upon vectorizing the innermost loop, it might look like this:

     for k = 1:n
       for i = 1:n
         dist(i,:) = min (dist(i,:), dist(i,k) + dist(k,:));
       endfor
     endfor

   Using broadcasting in both directions, it looks like this:

     for k = 1:n
       dist = min (dist, dist(:,k) + dist(k,:));
     endfor

   The relative time performance of the three techniques for a given
graph with 100 vertices is 7.3 seconds for the naive code, 87
milliseconds for the singly vectorized code, and 1.3 milliseconds for
the fully broadcast code.  For a graph with 1000 vertices, vectorization
takes 11.7 seconds while broadcasting takes only 1.15 seconds.
Therefore in general it is worth writing code with broadcasting
semantics for performance.

   However, beware of resorting to broadcasting if a simpler operation
will suffice.  For matrices A and B, consider the following:

     C = sum (permute (A, [1, 3, 2]) .* permute (B, [3, 2, 1]), 3);

This operation broadcasts the two matrices with permuted dimensions
across each other during elementwise multiplication in order to obtain a
larger 3-D array, and this array is then summed along the third
dimension.  A moment of thought will prove that this operation is simply
the much faster ordinary matrix multiplication, ‘C = A*B;’.

   A note on terminology: “broadcasting” is the term popularized by the
Numpy numerical environment in the Python programming language.  In
other programming languages and environments, broadcasting may also be
known as _binary singleton expansion_ (BSX, in MATLAB, and the origin of
the name of the ‘bsxfun’ function), _recycling_ (R programming
language), _single-instruction multiple data_ (SIMD), or _replication_.

19.2.1 Broadcasting and Legacy Code
-----------------------------------

The new broadcasting semantics almost never affect code that worked in
previous versions of Octave.  Consequently, all code inherited from
MATLAB that worked in previous versions of Octave should still work
without change in Octave.  The only exception is code such as

     try
       c = a.*b;
     catch
       c = a.*a;
     end_try_catch

that may have relied on matrices of different size producing an error.
Because such operation is now valid Octave syntax, this will no longer
produce an error.  Instead, the following code should be used:

     if (isequal (size (a), size (b)))
       c = a .* b;
     else
       c = a .* a;
     endif


File: octave.info,  Node: Function Application,  Next: Accumulation,  Prev: Broadcasting,  Up: Vectorization and Faster Code Execution

19.3 Function Application
=========================

As a general rule, functions should already be written with matrix
arguments in mind and should consider whole matrix operations in a
vectorized manner.  Sometimes, writing functions in this way appears
difficult or impossible for various reasons.  For those situations,
Octave provides facilities for applying a function to each element of an
array, cell, or struct.

 -- : arrayfun (FUNC, A)
 -- : X = arrayfun (FUNC, A)
 -- : X = arrayfun (FUNC, A, B, ...)
 -- : [X, Y, ...] = arrayfun (FUNC, A, ...)
 -- : arrayfun (..., "UniformOutput", VAL)
 -- : 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])
               ⇒ [ 1.57080   0.00000 ]

     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)
          ⇒
             {
               [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)
          ⇒
             {
               [1,1] = MyString
             }

     See also: *note spfun: XREFspfun, *note cellfun: XREFcellfun, *note
     structfun: XREFstructfun.

 -- : Y = spfun (F, S)
     Compute ‘f (S)’ for the nonzero elements of S.

     The input function F is applied only to the nonzero elements of the
     input matrix S which is typically sparse.  The function F can be
     passed as a string, function handle, or inline function.

     The output Y is a sparse matrix with the same sparsity structure as
     the input S.  ‘spfun’ preserves sparsity structure which is
     different than simply applying the function F to the sparse matrix
     S when ‘F (0) != 0’.

     Example

     Sparsity preserving ‘spfun’ versus normal function application

          S = pi * speye (2,2)
          S =

          Compressed Column Sparse (rows = 2, cols = 2, nnz = 2 [50%])

            (1, 1) -> 3.1416
            (2, 2) -> 3.1416

          y = spfun (@cos, S)
          y =

          Compressed Column Sparse (rows = 2, cols = 2, nnz = 2 [50%])

            (1, 1) -> -1
            (2, 2) -> -1

          y = cos (S)
          y =

          Compressed Column Sparse (rows = 2, cols = 2, nnz = 4 [100%])

            (1, 1) -> -1
            (2, 1) -> 1
            (1, 2) -> 1
            (2, 2) -> -1


     See also: *note arrayfun: XREFarrayfun, *note cellfun: XREFcellfun,
     *note structfun: XREFstructfun.

 -- : cellfun (NAME, C)
 -- : cellfun ("size", C, K)
 -- : cellfun ("isclass", C, CLASS)
 -- : cellfun (FUNC, C)
 -- : cellfun (FUNC, C, D)
 -- : [A, ...] = cellfun (...)
 -- : cellfun (..., "ErrorHandler", ERRFUNC)
 -- : cellfun (..., "UniformOutput", VAL)

     Evaluate the function named NAME on the elements of the cell array
     C.

     Elements in C are passed on to the named function individually.
     The function NAME can be one of the functions

     ‘isempty’
          Return 1 for empty elements.

     ‘islogical’
          Return 1 for logical elements.

     ‘isnumeric’
          Return 1 for numeric elements.

     ‘isreal’
          Return 1 for real elements.

     ‘length’
          Return a vector of the lengths of cell elements.

     ‘ndims’
          Return the number of dimensions of each element.

     ‘numel’
     ‘prodofsize’
          Return the number of elements contained within each cell
          element.  The number is the product of the dimensions of the
          object at each cell element.

     ‘size’
          Return the size along the K-th dimension.

     ‘isclass’
          Return 1 for elements of CLASS.

     Additionally, ‘cellfun’ accepts an arbitrary function FUNC in the
     form of an inline function, function handle, or the name of a
     function (in a character string).  The function can take one or
     more arguments, with the inputs arguments given by C, D, etc.
     Equally the function can return one or more output arguments.  For
     example:

          cellfun ("atan2", {1, 0}, {0, 1})
               ⇒ [ 1.57080   0.00000 ]

     The number of output arguments of ‘cellfun’ matches the number of
     output arguments of the function.  The outputs of the function will
     be collected into the output arguments of ‘cellfun’ like this:

          function [a, b] = twoouts (x)
            a = x;
            b = x*x;
          endfunction
          [aa, bb] = cellfun (@twoouts, {1, 2, 3})
               ⇒
                  aa =
                     1 2 3
                  bb =
                     1 4 9

     Note that per default the output argument(s) are arrays of the same
     size as the input arguments.  Input arguments that are singleton
     (1x1) cells will be automatically expanded to the size of the other
     arguments.

     If the parameter "UniformOutput" is set to true (the default), then
     the function must return scalars which will be concatenated into
     the return array(s).  If "UniformOutput" is false, the outputs are
     concatenated into a cell array (or cell arrays).  For example:

          cellfun ("tolower", {"Foo", "Bar", "FooBar"},
                   "UniformOutput", false)
          ⇒ {"foo", "bar", "foobar"}

     Given the parameter "ErrorHandler", then ERRFUNC defines a function
     to call in case FUNC generates an error.  The form of the function
     is

          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 into the input
     arguments of the element that caused the error.  For example:

          function y = foo (s, x), y = NaN; endfunction
          cellfun ("factorial", {-1,2}, "ErrorHandler", @foo)
          ⇒ [NaN 2]

     Use ‘cellfun’ intelligently.  The ‘cellfun’ function is a useful
     tool for avoiding loops.  It is often used with anonymous function
     handles; however, calling an anonymous function involves an
     overhead quite comparable to the overhead of an m-file function.
     Passing a handle to a built-in function is faster, because the
     interpreter is not involved in the internal loop.  For example:

          a = {...}
          v = cellfun (@(x) det (x), a); # compute determinants
          v = cellfun (@det, a); # faster

     See also: *note arrayfun: XREFarrayfun, *note structfun:
     XREFstructfun, *note spfun: XREFspfun.

 -- : structfun (FUNC, S)
 -- : [A, ...] = structfun (...)
 -- : structfun (..., "ErrorHandler", ERRFUNC)
 -- : structfun (..., "UniformOutput", VAL)

     Evaluate the function named NAME on the fields of the structure S.
     The fields of S are passed to the function FUNC individually.

     ‘structfun’ accepts an arbitrary function FUNC in the form of an
     inline function, function handle, or the name of a function (in a
     character string).  In the case of a character string argument, the
     function must accept a single argument named X, and it must return
     a string value.  If the function returns more than one argument,
     they are returned as separate output variables.

     If the parameter "UniformOutput" is set to true (the default), then
     the function must return a single element which will be
     concatenated into the return value.  If "UniformOutput" is false,
     the outputs are placed into a structure with the same fieldnames as
     the input structure.

          s.name1 = "John Smith";
          s.name2 = "Jill Jones";
          structfun (@(x) regexp (x, '(\w+)$', "matches"){1}, s,
                     "UniformOutput", false)
            ⇒ scalar structure containing the fields:
                 name1 = Smith
                 name2 = Jones

     Given the parameter "ErrorHandler", ERRFUNC defines a function to
     call in case FUNC generates an error.  The form of the function is

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

     where there is an additional input argument to ERRFUNC relative to
     FUNC, given by SE.  This is a structure with the elements
     "identifier", "message" and "index", giving respectively the error
     identifier, the error message, and the index into the input
     arguments of the element that caused the error.  For an example on
     how to use an error handler, *note ‘cellfun’: XREFcellfun.

     See also: *note cellfun: XREFcellfun, *note arrayfun: XREFarrayfun,
     *note spfun: XREFspfun.

   Consistent with earlier advice, seek to use Octave built-in functions
whenever possible for the best performance.  This advice applies
especially to the four functions above.  For example, when adding two
arrays together element-by-element one could use a handle to the
built-in addition function ‘@plus’ or define an anonymous function
‘@(x,y) x + y’.  But, the anonymous function is 60% slower than the
first method.  *Note Operator Overloading::, for a list of basic
functions which might be used in place of anonymous ones.

