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

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

END-INFO-DIR-ENTRY

   Copyright (C) 1996-2013 John W. Eaton.

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

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

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


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

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

A natural part of image processing is visualization of an image.  The
most basic function for this is the 'imshow' function that shows the
image given in the first input argument.

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

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

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

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

     If given, the parameter STRING_PARAM1 has value VALUE1.
     STRING_PARAM1 can be any of the following:

     "displayrange"
          VALUE1 is the display range as described above.

     "xdata"
          If VALUE1 is a two element vector, it must contain horizontal
          axis limits in the form [xmin xmax]; Otherwise VALUE1 must be
          a vector and only the first and last elements will be used for
          xmin and xmax respectively.

     "ydata"
          If VALUE1 is a two element vector, it must contain vertical
          axis limits in the form [ymin ymax]; Otherwise VALUE1 must be
          a vector and only the first and last elements will be used for
          ymin and ymax respectively.

     The optional return value H is a graphics handle to the image.

     See also: *note image: XREFimage, *note imagesc: XREFimagesc, *note
     colormap: XREFcolormap, *note gray2ind: XREFgray2ind, *note
     rgb2ind: XREFrgb2ind.

 -- Function File: image (IMG)
 -- Function File: image (X, Y, IMG)
 -- Function File: image (..., "PROP", VAL, ...)
 -- Function File: image ("PROP1", VAL1, ...)
 -- Function File: H = image (...)
     Display a matrix as an indexed color image.

     The elements of IMG are indices into the current colormap.  X and Y
     are optional 2-element vectors, '[min, max]', which specify the
     range for the axis labels.  If a range is specified as '[max, min]'
     then the image will be reversed along that axis.  For convenience,
     X and Y may be specified as N-element vectors matching the length
     of the data in IMG.  However, only the first and last elements will
     be used to determine the axis limits.  *Warning:* X and Y are
     ignored when using gnuplot 4.0 or earlier.

     Multiple property/value pairs may be specified for the image
     object, but they must appear in pairs.

     The optional return value H is a graphics handle to the image.

     Implementation Note: The origin (0, 0) for images is located in the
     upper left.  For ordinary plots, the origin is located in the lower
     left.  Octave handles this inversion by plotting the data normally,
     and then reversing the direction of the y-axis by setting the
     'ydir' property to "reverse".  This has implications whenever an
     image and an ordinary plot need to be overlaid.  The recommended
     solution is to display the image and then plot the reversed ydata
     using, for example, 'flipud (ydata)'.

     Calling Forms: The 'image' function can be called in two forms:
     High-Level and Low-Level.  When invoked with normal options, the
     High-Level form is used which first calls 'newplot' to prepare the
     graphic figure and axes.  When the only inputs to 'image' are
     property/value pairs the Low-Level form is used which creates a new
     instance of an image object and inserts it in the current axes.

     See also: *note imshow: XREFimshow, *note imagesc: XREFimagesc,
     *note colormap: XREFcolormap.

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

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

     The optional return value H is a graphics handle to the image.

     Calling Forms: The 'imagesc' function can be called in two forms:
     High-Level and Low-Level.  When invoked with normal options, the
     High-Level form is used which first calls 'newplot' to prepare the
     graphic figure and axes.  When the only inputs to 'image' are
     property/value pairs the Low-Level form is used which creates a new
     instance of an image object and inserts it in the current axes.

     See also: *note image: XREFimage, *note imshow: XREFimshow, *note
     caxis: XREFcaxis.


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

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

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

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

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

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

 -- Function File: iscolormap (CMAP)
     Return true if CMAP is a colormap.

     A colormap is a real matrix with N rows and 3 columns.  Each row
     represents a single color.  The columns contain red, green, and
     blue intensities respectively.  All entries must be between 0 and 1
     inclusive.

     See also: *note colormap: XREFcolormap, *note rgbplot: XREFrgbplot.

 -- Function File: IMG = gray2ind (I)
 -- Function File: IMG = gray2ind (I, N)
 -- Function File: IMG = gray2ind (BW)
 -- Function File: IMG = gray2ind (BW, N)
 -- Function File: [IMG, MAP] = gray2ind (...)
     Convert a grayscale or binary intensity image to an indexed image.

     The indexed image will consist of N different intensity values.  If
     not given N defaults to 64 for grayscale images or 2 for binary
     black and white images.

     The output IMG is of class uint8 if N is less than or equal to 256;
     Otherwise the return class is uint16.

     See also: *note ind2gray: XREFind2gray, *note rgb2ind: XREFrgb2ind.

 -- Function File: I = ind2gray (X, MAP)
     Convert a color indexed image to a grayscale intensity image.

     The image X must be an indexed image which will be converted using
     the colormap CMAP.  If CMAP does not contain enough colors for the
     image, pixels in X outside the range are mapped to the last color
     in the map before conversion to grayscale.

     The output I is of the same class as the input X and may be one of
     'uint8', 'uint16', 'single', or 'double'.

     Implementation Note: There are several ways of converting colors to
     grayscale intensities.  This functions uses the luminance value
     obtained from 'rgb2ntsc' which is 'I = 0.299*R + 0.587*G +
     0.114*B'.  Other possibilities include the value component from
     'rgb2hsv' or using a single color channel from 'ind2rgb'.

     See also: *note gray2ind: XREFgray2ind, *note ind2rgb: XREFind2rgb.

 -- Function File: [X, MAP] = rgb2ind (RGB)
 -- Function File: [X, MAP] = rgb2ind (R, G, B)
     Convert an image in red-green-blue (RGB) color space to an indexed
     image.

     The input image RGB can be specified as a single matrix of size
     MxNx3, or as three separate variables, R, G, and B, its three
     colour channels, red, green, and blue.

     It outputs an indexed image X and a colormap MAP to interpret an
     image exactly the same as the input.  No dithering or other form of
     color quantization is performed.  The output class of the indexed
     image X can be uint8, uint16 or double, whichever is required to
     specify the number of unique colors in the image (which will be
     equal to the number of rows in MAP) in order

     Multi-dimensional indexed images (of size MxNx3xK) are also
     supported, both via a single input (RGB) or its three colour
     channels as separate variables.

     See also: *note ind2rgb: XREFind2rgb, *note rgb2hsv: XREFrgb2hsv,
     *note rgb2ntsc: XREFrgb2ntsc.

 -- Function File: RGB = ind2rgb (X, MAP)
 -- Function File: [R, G, B] = ind2rgb (X, MAP)
     Convert an indexed image to red, green, and blue color components.

     The image X must be an indexed image which will be converted using
     the colormap MAP.  If MAP does not contain enough colors for the
     image, pixels in X outside the range are mapped to the last color
     in the map.

     The output may be a single RGB image (MxNx3 matrix where M and N
     are the original image X dimensions, one for each of the red, green
     and blue channels).  Alternatively, the individual red, green, and
     blue color matrices of size MxN may be returned.

     Multi-dimensional indexed images (of size MxNx1xK) are also
     supported.

     See also: *note rgb2ind: XREFrgb2ind, *note ind2gray: XREFind2gray,
     *note hsv2rgb: XREFhsv2rgb, *note ntsc2rgb: XREFntsc2rgb.

 -- Function File: CMAP = colormap ()
 -- Function File: CMAP = colormap (MAP)
 -- Function File: CMAP = colormap ("default")
 -- Function File: CMAP = colormap ("MAP_NAME")
 -- Function File: CMAP = colormap (HAX, ...)
 -- Command: colormap MAP_NAME
 -- Function File: CMAPS = colormap ("list")
 -- Function File: colormap ("register", "NAME")
 -- Function File: colormap ("unregister", "NAME")
     Query or set the current colormap.

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

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

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

     The map may also be specified by a string, "MAP_NAME", where
     MAP_NAME is the name of a function that returns a colormap.

     If the first argument HAX is an axes handle, then the colormap for
     the parent figure of HAX is queried or set.

     For convenience, it is also possible to use this function with the
     command form, 'colormap MAP_NAME'.

     'colormap ("list")' returns a cell array with all of the available
     colormaps.  The options "register" and "unregister" add or remove
     the colormap NAME from this list.

     See also: *note jet: XREFjet.

 -- Function File: rgbplot (CMAP)
 -- Function File: rgbplot (CMAP, STYLE)
 -- Function File: H = rgbplot (...)
     Plot the components of a colormap.

     Two different STYLEs are available for displaying the CMAP:

     profile (default)
          Plot the RGB line profile of the colormap for each of the
          channels (red, green and blue) with the plot lines colored
          appropriately.  Each line represents the intensity of each RGB
          components across the colormap.

     composite
          Draw the colormap across the X-axis so that the actual index
          colors are visible rather than the individual color
          components.

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

     Run 'demo rgbplot' to see an example of 'rgbplot' and each style
     option.

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = autumn ()
 -- Function File: MAP = autumn (N)
     Create color colormap.  This colormap ranges from red through
     orange to yellow.  The argument N must be a scalar.  If
     unspecified, the length of the current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = bone ()
 -- Function File: MAP = bone (N)
     Create color colormap.  This colormap varies from black to white
     with gray-blue shades.  The argument N must be a scalar.  If
     unspecified, the length of the current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = colorcube ()
 -- Function File: MAP = colorcube (N)
     Create color colormap.  This colormap is composed of as many
     equally spaced colors (not grays) in the RGB color space as
     possible.  If there are not a perfect number N of regularly spaced
     colors then the remaining entries in the colormap are gradients of
     pure red, green, blue, and gray.  The argument N must be a scalar.
     If unspecified, the length of the current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = cool ()
 -- Function File: MAP = cool (N)
     Create color colormap.  The colormap varies from cyan to magenta.
     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = copper ()
 -- Function File: MAP = copper (N)
     Create color colormap.  This colormap varies from black to a light
     copper tone.  The argument N must be a scalar.  If unspecified, the
     length of the current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = flag ()
 -- Function File: MAP = flag (N)
     Create color colormap.  This colormap cycles through red, white,
     blue, and black with each index change.  The argument N must be a
     scalar.  If unspecified, the length of the current colormap, or 64,
     is used.

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = gray ()
 -- Function File: MAP = gray (N)
     Create gray colormap.  This colormap varies from black to white
     with shades of gray.  The argument N must be a scalar.  If
     unspecified, the length of the current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = hot ()
 -- Function File: MAP = hot (N)
     Create color colormap.  This colormap ranges from black through
     dark red, red, orange, yellow, to white.  The argument N must be a
     scalar.  If unspecified, the length of the current colormap, or 64,
     is used.

     See also: *note colormap: XREFcolormap.

 -- Function File: hsv (N)
     Create color colormap.  This colormap begins with red, changes
     through yellow, green, cyan, blue, and magenta, before returning to
     red.  It is useful for displaying periodic functions.  The map is
     obtained by linearly varying the hue through all possible values
     while keeping constant maximum saturation and value.  The
     equivalent code is 'hsv2rgb ([(0:N-1)'/N, ones(N,2)])'.

     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = jet ()
 -- Function File: MAP = jet (N)
     Create color colormap.  This colormap ranges from dark blue through
     blue, cyan, green, yellow, red, to dark red.  The argument N must
     be a scalar.  If unspecified, the length of the current colormap,
     or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = lines ()
 -- Function File: MAP = lines (N)
     Create color colormap.  This colormap is composed of the list of
     colors in the current axes "ColorOrder" property.  The default is
     blue, green, red, cyan, pink, yellow, and gray.  The argument N
     must be a scalar.  If unspecified, the length of the current
     colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = ocean ()
 -- Function File: MAP = ocean (N)
     Create color colormap.  This colormap varies from black to white
     with shades of blue.  The argument N must be a scalar.  If
     unspecified, the length of the current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = pink ()
 -- Function File: MAP = pink (N)
     Create color colormap.  This colormap varies from black to white
     with shades of gray-pink.  It gives a sepia tone when used on
     grayscale images.  The argument N must be a scalar.  If
     unspecified, the length of the current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = prism ()
 -- Function File: MAP = prism (N)
     Create color colormap.  This colormap cycles through red, orange,
     yellow, green, blue and violet with each index change.  The
     argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = rainbow ()
 -- Function File: MAP = rainbow (N)
     Create color colormap.  This colormap ranges from red through
     orange, yellow, green, blue, to violet.  The argument N must be a
     scalar.  If unspecified, the length of the current colormap, or 64,
     is used.

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = spring ()
 -- Function File: MAP = spring (N)
     Create color colormap.  This colormap varies from magenta to
     yellow.  The argument N must be a scalar.  If unspecified, the
     length of the current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = summer ()
 -- Function File: MAP = summer (N)
     Create color colormap.  This colormap varies from green to yellow.
     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

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

     See also: *note colormap: XREFcolormap.

 -- Function File: MAP = winter ()
 -- Function File: MAP = winter (N)
     Create color colormap.  This colormap varies from blue to green.
     The argument N must be a scalar.  If unspecified, the length of the
     current colormap, or 64, is used.

     See also: *note colormap: XREFcolormap.

 -- Function File: CMAP = contrast (X)
 -- Function File: CMAP = contrast (X, N)
     Return a gray colormap that maximizes the contrast in an image.
     The returned colormap will have N rows.  If N is not defined then
     the size of the current colormap is used.

     See also: *note colormap: XREFcolormap, *note brighten:
     XREFbrighten.

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

 -- Function File: MAP = gmap40 ()
 -- Function File: MAP = gmap40 (N)
     Create color colormap.  The colormap consists of red, green, blue,
     yellow, magenta and cyan.  This colormap is specifically designed
     for users of gnuplot 4.0 where these 6 colors are the allowable
     ones for patch objects.  The argument N must be a scalar.  If
     unspecified, a length of 6 is assumed.  Larger values of N result
     in a repetition of the above colors.

     See also: *note colormap: XREFcolormap.

   The following three functions modify the existing colormap rather
than replace it.

 -- Function File: MAP_OUT = brighten (MAP, BETA)
 -- Function File: MAP_OUT = brighten (BETA)
 -- Function File: MAP_OUT = brighten (H, BETA)
     Brighten or darken a colormap.  If the MAP argument is omitted, the
     function is applied to the current colormap.  The first argument
     can also be a valid graphics handle H, in which case 'brighten' is
     applied to the colormap associated with this handle.

     The argument BETA must be a scalar between -1 and 1, where a
     negative value darkens and a positive value brightens the colormap.

     If no output is specified then the result is written to the current
     colormap.

     See also: *note colormap: XREFcolormap, *note contrast:
     XREFcontrast.

 -- Function File: spinmap ()
 -- Function File: spinmap (T)
 -- Function File: spinmap (T, INC)
 -- Function File: spinmap ("inf")
     Cycle the colormap for T seconds with a color increment of INC.
     Both parameters are optional.  The default cycle time is 5 seconds
     and the default increment is 2.  If the option "inf" is given then
     cycle continuously until 'Control-C' is pressed.

     When rotating the original color 1 becomes color 2, color 2 becomes
     color 3, etc.  A positive or negative increment is allowed and a
     higher value of INC will cause faster cycling through the colormap.

     See also: *note colormap: XREFcolormap.

 -- Function File: whitebg ()
 -- Function File: whitebg (COLOR)
 -- Function File: whitebg ("none")
 -- Function File: whitebg (HFIG, ...)
     Invert the colors in the current color scheme.

     The root properties are also inverted such that all subsequent plot
     use the new color scheme.

     If the optional argument COLOR is present then the background color
     is set to COLOR rather than inverted.  COLOR may be a string
     representing one of the eight known colors or an RGB triplet.  The
     special string argument "none" restores the plot to the default
     colors.

     If the first argument HFIG is a figure handle, then operate on this
     figure rather than the current figure returned by 'gcf'.  The root
     properties will not be changed.

     See also: *note reset: XREFreset, *note get: XREFget, *note set:
     XREFset.

   The following functions can be used to manipulate colormaps.

 -- Function File: [Y, NEWMAP] = cmunique (X, MAP)
 -- Function File: [Y, NEWMAP] = cmunique (RGB)
 -- Function File: [Y, NEWMAP] = cmunique (I)
     Convert an input image X to an ouput indexed image Y which uses the
     smallest colormap possible NEWMAP.

     When the input is an indexed image (X with colormap MAP) the output
     is a colormap NEWMAP from which any repeated rows have been
     eliminated.  The output image, Y, is the original input image with
     the indices adjusted to match the new, possibly smaller, colormap.

     When the input is an RGB image (an MxNx3 array), the output
     colormap will contain one entry for every unique color in the
     original image.  In the worst case the new map could have as many
     rows as the number of pixels in the original image.

     When the input is a grayscale image I, the output colormap will
     contain one entry for every unique intensity value in the original
     image.  In the worst case the new map could have as many rows as
     the number of pixels in the original image.

     Implementation Details:

     NEWMAP is always an Mx3 matrix, even if the input image is an
     intensity grayscale image I (all three RGB planes are assigned the
     same value).

     The output image is of class uint8 if the size of the new colormap
     is less than or equal to 256.  Otherwise, the output image is of
     class double.

     See also: *note rgb2ind: XREFrgb2ind, *note gray2ind: XREFgray2ind.

 -- Function File: [Y, NEWMAP] = cmpermute (X, MAP)
 -- Function File: [Y, NEWMAP] = cmpermute (X, MAP, INDEX)
     Reorder colors in a colormap.

     When called with only two arguments, 'cmpermute' randomly
     rearranges the colormap MAP and returns a new colormap NEWMAP.  It
     also returns the indexed image Y which is the equivalent of the
     original input image X when displayed using NEWMAP.

     When called with an optional third argument the order of colors in
     the new colormap is defined by INDEX.

     *Caution:* 'index' should not have repeated elements or the
     function will fail.


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

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

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

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


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

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

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

 -- Function File: HSV_MAP = rgb2hsv (RGB)
 -- Function File: HSV_MAP = rgb2hsv (RGB)
     Transform a colormap or image from red-green-blue (RGB) space to
     hue-saturation-value (HSV) space.

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

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

     See also: *note hsv2rgb: XREFhsv2rgb, *note rgb2ind: XREFrgb2ind,
     *note rgb2ntsc: XREFrgb2ntsc.

 -- Function File: RGB_MAP = hsv2rgb (HSV_MAP)
 -- Function File: RGB_IMG = hsv2rgb (HSV_IMG)
     Transform a colormap or image from hue-saturation-value (HSV) space
     to red-green-blue (RGB) space.

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

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

     See also: *note rgb2hsv: XREFrgb2hsv, *note ind2rgb: XREFind2rgb,
     *note ntsc2rgb: XREFntsc2rgb.

 -- Function File: YIQ_MAP = rgb2ntsc (RGB_MAP)
 -- Function File: YIQ_IMG = rgb2ntsc (RGB_IMG)
     Transform a colormap or image from red-green-blue (RGB) color space
     to luminance-chrominance (NTSC) space.  The input may be of class
     uint8, uint16, single, or double.  The output is of class double.

     Implementation Note: The reference matrix for the transformation is

          /Y\     0.299  0.587  0.114  /R\
          |I|  =  0.596 -0.274 -0.322  |G|
          \Q/     0.211 -0.523  0.312  \B/

     as documented in <http://en.wikipedia.org/wiki/YIQ> and truncated
     to 3 significant figures.  Note: The FCC version of NTSC uses only
     2 significant digits and is slightly different.

     See also: *note ntsc2rgb: XREFntsc2rgb, *note rgb2hsv: XREFrgb2hsv,
     *note rgb2ind: XREFrgb2ind.

 -- Function File: RGB_MAP = ntsc2rgb (YIQ_MAP)
 -- Function File: RGB_IMG = ntsc2rgb (YIQ_IMG)
     Transform a colormap or image from luminance-chrominance (NTSC)
     space to red-green-blue (RGB) color space.

     Implementation Note: The conversion matrix is chosen to be the
     inverse of the matrix used for rgb2ntsc such that

          x == ntsc2rgb (rgb2ntsc (x))

     MATLAB uses a slightly different matrix where rounding means the
     equality above does not hold.

     See also: *note rgb2ntsc: XREFrgb2ntsc, *note hsv2rgb: XREFhsv2rgb,
     *note ind2rgb: XREFind2rgb.


File: octave.info,  Node: Audio Processing,  Next: Object Oriented Programming,  Prev: Image Processing,  Up: Top

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

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

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

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

 -- Function File: lin2mu (X, N)
     Convert audio data from linear to mu-law.  Mu-law values use 8-bit
     unsigned integers.  Linear values use N-bit signed integers or
     floating point values in the range -1 <= X <= 1 if N is 0.

     If N is not specified it defaults to 0, 8, or 16 depending on the
     range of values in X.

     See also: *note mu2lin: XREFmu2lin, *note loadaudio: XREFloadaudio,
     *note saveaudio: XREFsaveaudio.

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

     If N is not specified it defaults to 0.

     See also: *note lin2mu: XREFlin2mu, *note loadaudio: XREFloadaudio,
     *note saveaudio: XREFsaveaudio.

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

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

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

     See also: *note lin2mu: XREFlin2mu, *note mu2lin: XREFmu2lin, *note
     saveaudio: XREFsaveaudio, *note playaudio: XREFplayaudio, *note
     setaudio: XREFsetaudio, *note record: XREFrecord.

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

     See also: *note lin2mu: XREFlin2mu, *note mu2lin: XREFmu2lin, *note
     loadaudio: XREFloadaudio, *note playaudio: XREFplayaudio, *note
     setaudio: XREFsetaudio, *note record: XREFrecord.

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

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

     See also: *note lin2mu: XREFlin2mu, *note mu2lin: XREFmu2lin, *note
     loadaudio: XREFloadaudio, *note saveaudio: XREFsaveaudio, *note
     setaudio: XREFsetaudio, *note record: XREFrecord.

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

     See also: *note lin2mu: XREFlin2mu, *note mu2lin: XREFmu2lin, *note
     loadaudio: XREFloadaudio, *note saveaudio: XREFsaveaudio, *note
     playaudio: XREFplayaudio, *note setaudio: XREFsetaudio.

 -- Function File: setaudio ()
 -- Function File: setaudio (W_TYPE)
 -- Function File: setaudio (W_TYPE, VALUE)
     Execute the shell command 'mixer', possibly with optional arguments
     W_TYPE and VALUE.

 -- Function File: Y = wavread (FILENAME)
 -- Function File: [Y, FS, BPS] = wavread (FILENAME)
 -- Function File: [...] = wavread (FILENAME, N)
 -- Function File: [...] = wavread (FILENAME, [N1 N2])
 -- Function File: [SAMPLES, CHANNELS] = wavread (FILENAME, "size")

     Load the RIFF/WAVE sound file FILENAME, and return the samples in
     vector Y.  If the file contains multichannel data, then Y is a
     matrix with the channels represented as columns.

     '[Y, FS, BPS] = wavread (FILENAME)'

     Additionally return the sample rate (FS) in Hz and the number of
     bits per sample (BPS).

     '[...] = wavread (FILENAME, N)'

     Read only the first N samples from each channel.

     'wavread (FILENAME, [N1 N2])'

     Read only samples N1 through N2 from each channel.

     '[SAMPLES, CHANNELS] = wavread (FILENAME, "size")'

     Return the number of samples (N) and number of channels (CH)
     instead of the audio data.

     See also: *note wavwrite: XREFwavwrite.

 -- Function File: wavwrite (Y, FILENAME)
 -- Function File: wavwrite (Y, FS, FILENAME)
 -- Function File: wavwrite (Y, FS, BPS, FILENAME)
     Write Y to the canonical RIFF/WAVE sound file FILENAME with sample
     rate FS and bits per sample BPS.  The default sample rate is 8000
     Hz with 16-bits per sample.  Each column of the data represents a
     separate channel.  If Y is either a row vector or a column vector,
     it is written as a single channel.

     See also: *note wavread: XREFwavread.


File: octave.info,  Node: Object Oriented Programming,  Next: GUI Development,  Prev: Audio Processing,  Up: Top

34 Object Oriented Programming
******************************

Octave includes the capability to include user classes, including the
features of operator and function overloading.  Equally a user class can
be used to encapsulate certain properties of the class so that they
cannot be altered accidentally and can be set up to address the issue of
class precedence in mixed class operations.

   This chapter discussions the means of constructing a user class with
the example of a polynomial class, how to query and set the properties
of this class, together with the means to overload operators and
functions.

* Menu:

* Creating a Class::
* Manipulating Classes::
* Indexing Objects::
* Overloading Objects::
* Inheritance and Aggregation::


File: octave.info,  Node: Creating a Class,  Next: Manipulating Classes,  Up: Object Oriented Programming

34.1 Creating a Class
=====================

We use in the following text a polynomial class to demonstrate the use
of object oriented programming within Octave.  This class was chosen as
it is simple, and so doesn't distract unnecessarily from the discussion
of the programming features of Octave.  However, even still a small
understand of the polynomial class itself is necessary to fully grasp
the techniques described.

   The polynomial class is used to represent polynomials of the form

     a0 + a1 * x + a2 * x^2 + ... + an * x^n

where a0, a1, etc.  are real scalars.  Thus the polynomial can be
represented by a vector

     a = [a0, a1, a2, ..., an];

   We therefore now have sufficient information about the requirements
of the class constructor for our polynomial class to write it.  All
object oriented classes in Octave, must be contained with a directory
taking the name of the class, prepended with the @ symbol.  For example,
with our polynomial class, we would place the methods defining the class
in the @polynomial directory.

   The constructor of the class, must have the name of the class itself
and so in our example the constructor with have the name
'@polynomial/polynomial.m'.  Also ideally when the constructor is called
with no arguments to should return a value object.  So for example our
polynomial might look like

     ## -*- texinfo -*-
     ## @deftypefn  {Function File} {} polynomial ()
     ## @deftypefnx {Function File} {} polynomial (@var{a})
     ## Create a polynomial object representing the polynomial
     ##
     ## @example
     ## a0 + a1 * x + a2 * x^2 + @dots{} + an * x^n
     ## @end example
     ##
     ## @noindent
     ## from a vector of coefficients [a0 a1 a2 @dots{} an].
     ## @end deftypefn

     function p = polynomial (a)
       if (nargin == 0)
         p.poly = [0];
         p = class (p, "polynomial");
       elseif (nargin == 1)
         if (strcmp (class (a), "polynomial"))
           p = a;
         elseif (isvector (a) && isreal (a))
           p.poly = a(:).';
           p = class (p, "polynomial");
         else
           error ("polynomial: expecting real vector");
         endif
       else
         print_usage ();
       endif
     endfunction


   Note that the return value of the constructor must be the output of
the 'class' function called with the first argument being a structure
and the second argument being the class name.  An example of the call to
this constructor function is then

     p = polynomial ([1, 0, 1]);

   Note that methods of a class can be documented.  The help for the
constructor itself can be obtained with the constructor name, that is
for the polynomial constructor 'help polynomial' will return the help
string.  Also the help can be obtained by restricting the search for the
help to a particular class, for example 'help @polynomial/polynomial'.
This second method is the only means of getting help for the overloaded
methods and functions of the class.

   The same is true for other Octave functions that take a function name
as an argument.  For example 'type @polynomial/display' will print the
code of the display method of the polynomial class to the screen, and
'dbstop @polynomial/display' will set a breakpoint at the first
executable line of the display method of the polynomial class.

   To check where a variable is a user class, the 'isobject' and 'isa'
functions can be used.  For example:

     p = polynomial ([1, 0, 1]);
     isobject (p)
       => 1
     isa (p, "polynomial")
       => 1

 -- Built-in Function: isobject (X)
     Return true if X is a class object.

     See also: *note class: XREFclass, *note typeinfo: XREFtypeinfo,
     *note isa: XREFisa, *note ismethod: XREFismethod.

The available methods of a class can be displayed with the 'methods'
function.

 -- Function File: methods (OBJ)
 -- Function File: methods ("CLASSNAME")
 -- Function File: MTDS = methods (...)

     Return a cell array containing the names of the methods for the
     object OBJ or the named class CLASSNAME.  OBJ may be an Octave
     class object or a Java object.

     See also: *note fieldnames: XREFfieldnames.

To inquire whether a particular method is available to a user class, the
'ismethod' function can be used.

 -- Built-in Function: ismethod (X, METHOD)
     Return true if X is a class object and the string METHOD is a
     method of this class.

     See also: *note isobject: XREFisobject.

For example:

     p = polynomial ([1, 0, 1]);
     ismethod (p, "roots")
       => 1


File: octave.info,  Node: Manipulating Classes,  Next: Indexing Objects,  Prev: Creating a Class,  Up: Object Oriented Programming

34.2 Manipulating Classes
=========================

There are a number of basic classes methods that can be defined to allow
the contents of the classes to be queried and set.  The most basic of
these is the 'display' method.  The 'display' method is used by Octave
when displaying a class on the screen, due to an expression that is not
terminated with a semicolon.  If this method is not defined, then Octave
will printed nothing when displaying the contents of a class.

 -- Function File: display (A)
     Display the contents of an object.  If A is an object of the class
     "myclass", then 'display' is called in a case like

          myclass (...)

     where Octave is required to display the contents of a variable of
     the type "myclass".

     See also: *note class: XREFclass, *note subsref: XREFsubsref, *note
     subsasgn: XREFsubsasgn.

An example of a display method for the polynomial class might be

     function display (p)
       a = p.poly;
       first = true;
       fprintf ("%s =", inputname (1));
       for i = 1 : length (a);
         if (a(i) != 0)
           if (first)
             first = false;
           elseif (a(i) > 0)
             fprintf (" +");
           endif
           if (a(i) < 0)
             fprintf (" -");
           endif
           if (i == 1)
             fprintf (" %g", abs (a(i)));
           elseif (abs(a(i)) != 1)
             fprintf (" %g *", abs (a(i)));
           endif
           if (i > 1)
             fprintf (" X");
           endif
           if (i > 2)
             fprintf (" ^ %d", i - 1);
           endif
         endif
       endfor
       if (first)
         fprintf (" 0");
       endif
       fprintf ("\n");
     endfunction


Note that in the display method, it makes sense to start the method with
the line 'fprintf ("%s =", inputname (1))' to be consistent with the
rest of Octave and print the variable name to be displayed when
displaying the class.

   To be consistent with the Octave graphic handle classes, a class
should also define the 'get' and 'set' methods.  The 'get' method should
accept one or two arguments, and given one argument of the appropriate
class it should return a structure with all of the properties of the
class.  For example:

     function s = get (p, f)
       if (nargin == 1)
         s.poly = p.poly;
       elseif (nargin == 2)
         if (ischar (f))
           switch (f)
             case "poly"
               s = p.poly;
             otherwise
               error ("get: invalid property %s", f);
           endswitch
         else
           error ("get: expecting the property to be a string");
         endif
       else
         print_usage ();
       endif
     endfunction


Similarly, the 'set' method should taken as its first argument an object
to modify, and then take property/value pairs to be modified.

     function s = set (p, varargin)
       s = p;
       if (length (varargin) < 2 || rem (length (varargin), 2) != 0)
         error ("set: expecting property/value pairs");
       endif
       while (length (varargin) > 1)
         prop = varargin{1};
         val = varargin{2};
         varargin(1:2) = [];
         if (ischar (prop) && strcmp (prop, "poly"))
           if (isvector (val) && isreal (val))
             s.poly = val(:).';
           else
             error ("set: expecting the value to be a real vector");
           endif
         else
           error ("set: invalid property of polynomial class");
         endif
       endwhile
     endfunction


Note that as Octave does not implement pass by reference, than the
modified object is the return value of the 'set' method and it must be
called like

     p = set (p, "a", [1, 0, 0, 0, 1]);

Also the 'set' method makes use of the 'subsasgn' method of the class,
and this method must be defined.  The 'subsasgn' method is discussed in
the next section.

   Finally, user classes can be considered as a special type of a
structure, and so they can be saved to a file in the same manner as a
structure.  For example:

     p = polynomial ([1, 0, 1]);
     save userclass.mat p
     clear p
     load userclass.mat

All of the file formats supported by 'save' and 'load' are supported.
In certain circumstances, a user class might either contain a field that
it makes no sense to save or a field that needs to be initialized before
it is saved.  This can be done with the 'saveobj' method of the class

 -- Function File: B = saveobj (A)
     Method of a class to manipulate an object prior to saving it to a
     file.  The function 'saveobj' is called when the object A is saved
     using the 'save' function.  An example of the use of 'saveobj'
     might be to remove fields of the object that don't make sense to be
     saved or it might be used to ensure that certain fields of the
     object are initialized before the object is saved.  For example:

          function b = saveobj (a)
            b = a;
            if (isempty (b.field))
               b.field = initfield (b);
            endif
          endfunction

     See also: *note loadobj: XREFloadobj, *note class: XREFclass.

'saveobj' is called just prior to saving the class to a file.  Likely,
the 'loadobj' method is called just after a class is loaded from a file,
and can be used to ensure that any removed fields are reinserted into
the user object.

 -- Function File: B = loadobj (A)
     Method of a class to manipulate an object after loading it from a
     file.  The function 'loadobj' is called when the object A is loaded
     using the 'load' function.  An example of the use of 'saveobj'
     might be to add fields to an object that don't make sense to be
     saved.  For example:

          function b = loadobj (a)
            b = a;
            b.addmissingfield = addfield (b);
          endfunction

     See also: *note saveobj: XREFsaveobj, *note class: XREFclass.


File: octave.info,  Node: Indexing Objects,  Next: Overloading Objects,  Prev: Manipulating Classes,  Up: Object Oriented Programming

34.3 Indexing Objects
=====================

* Menu:

* Defining Indexing And Indexed Assignment::
* Indexed Assignment Optimization::


File: octave.info,  Node: Defining Indexing And Indexed Assignment,  Next: Indexed Assignment Optimization,  Up: Indexing Objects

34.3.1 Defining Indexing And Indexed Assignment
-----------------------------------------------

Objects can be indexed with parentheses, either like 'A (IDX)' or like
'A {IDX}', or even like 'A (IDX).FIELD'.  However, it is up to the user
to decide what this indexing actually means.  In the case of our
polynomial class 'P (N)' might mean either the coefficient of the N-th
power of the polynomial, or it might be the evaluation of the polynomial
at N.  The meaning of this subscripted referencing is determined by the
'subsref' method.

 -- Built-in Function: subsref (VAL, IDX)
     Perform the subscripted element selection operation according to
     the subscript specified by IDX.

     The subscript IDX is expected to be a structure array with fields
     'type' and 'subs'.  Valid values for 'type' are '"()"', '"{}"', and
     '"."'.  The 'subs' field may be either '":"' or a cell array of
     index values.

     The following example shows how to extract the two first columns of
     a matrix

          val = magic (3)
              => val = [ 8   1   6
                         3   5   7
                         4   9   2 ]
          idx.type = "()";
          idx.subs = {":", 1:2};
          subsref (val, idx)
               => [ 8   1
                    3   5
                    4   9 ]

     Note that this is the same as writing 'val(:,1:2)'.

     If IDX is an empty structure array with fields 'type' and 'subs',
     return VAL.

     See also: *note subsasgn: XREFsubsasgn, *note substruct:
     XREFsubstruct.

   For example we might decide that indexing with "()" evaluates the
polynomial and indexing with "{}" returns the N-th coefficient (of N-th
power).  In this case the 'subsref' method of our polynomial class might
look like

     function b = subsref (a, s)
       if (isempty (s))
         error ("polynomial: missing index");
       endif
       switch (s(1).type)
         case "()"
           ind = s(1).subs;
           if (numel (ind) != 1)
             error ("polynomial: need exactly one index");
           else
             b = polyval (fliplr (a.poly), ind{1});
           endif
         case "{}"
           ind = s(1).subs;
           if (numel (ind) != 1)
             error ("polynomial: need exactly one index");
           else
             if (isnumeric (ind{1}))
               b = a.poly(ind{1}+1);
             else
               b = a.poly(ind{1});
             endif
           endif
         case "."
           fld = s.subs;
           if (strcmp (fld, "poly"))
             b = a.poly;
           else
             error ("@polynomial/subsref: invalid property \"%s\"", fld);
           endif
         otherwise
           error ("invalid subscript type");
       endswitch
       if (numel (s) > 1)
         b = subsref (b, s(2:end));
       endif
     endfunction


   The equivalent functionality for subscripted assignments uses the
'subsasgn' method.

 -- Built-in Function: subsasgn (VAL, IDX, RHS)
     Perform the subscripted assignment operation according to the
     subscript specified by IDX.

     The subscript IDX is expected to be a structure array with fields
     'type' and 'subs'.  Valid values for 'type' are '"()"', '"{}"', and
     '"."'.  The 'subs' field may be either '":"' or a cell array of
     index values.

     The following example shows how to set the two first columns of a
     3-by-3 matrix to zero.

          val = magic (3);
          idx.type = "()";
          idx.subs = {":", 1:2};
          subsasgn (val, idx, 0)
               =>  [ 0   0   6
                     0   0   7
                     0   0   2 ]

     Note that this is the same as writing 'val(:,1:2) = 0'.

     If IDX is an empty structure array with fields 'type' and 'subs',
     return RHS.

     See also: *note subsref: XREFsubsref, *note substruct:
     XREFsubstruct.

 -- Built-in Function: VAL = optimize_subsasgn_calls ()
 -- Built-in Function: OLD_VAL = optimize_subsasgn_calls (NEW_VAL)
 -- Built-in Function: optimize_subsasgn_calls (NEW_VAL, "local")
     Query or set the internal flag for subsasgn method call
     optimizations.  If true, Octave will attempt to eliminate the
     redundant copying when calling subsasgn method of a user-defined
     class.

     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.

   Note that the 'subsref' and 'subsasgn' methods always receive the
whole index chain, while they usually handle only the first element.  It
is the responsibility of these methods to handle the rest of the chain
(if needed), usually by forwarding it again to 'subsref' or 'subsasgn'.

   If you wish to use the 'end' keyword in subscripted expressions of an
object, then the user needs to define the 'end' method for the class.
For example, the 'end' method for our polynomial class might look like

     function r = end (obj, index_pos, num_indices)

       if (num_indices != 1)
         error ("polynomial object may only have one index")
       endif

       r = length (obj.poly) - 1;

     endfunction


which is a fairly generic 'end' method that has a behavior similar to
the 'end' keyword for Octave Array classes.  It can then be used as
follows:

     p = polynomial ([1,2,3,4]);
     p(end-1)
       => 3

   Objects can also be used as the index in a subscripted expression
themselves and this is controlled with the 'subsindex' function.

 -- Function File: IDX = subsindex (A)
     Convert an object to an index vector.  When A is a class object
     defined with a class constructor, then 'subsindex' is the
     overloading method that allows the conversion of this class object
     to a valid indexing vector.  It is important to note that
     'subsindex' must return a zero-based real integer vector of the
     class "double".  For example, if the class constructor

          function b = myclass (a)
            b = class (struct ("a", a), "myclass");
          endfunction

     then the 'subsindex' function

          function idx = subsindex (a)
            idx = double (a.a) - 1.0;
          endfunction

     can then be used as follows

          a = myclass (1:4);
          b = 1:10;
          b(a)
          => 1  2  3  4

     See also: *note class: XREFclass, *note subsref: XREFsubsref, *note
     subsasgn: XREFsubsasgn.

   Finally, objects can equally be used like ranges, using the 'colon'
method

 -- Function File: R = colon (A, B)
 -- Function File: R = colon (A, B, C)
     Method of a class to construct a range with the ':' operator.  For
     example:

          a = myclass (...);
          b = myclass (...);
          c = a : b

     See also: *note class: XREFclass, *note subsref: XREFsubsref, *note
     subsasgn: XREFsubsasgn.


File: octave.info,  Node: Indexed Assignment Optimization,  Prev: Defining Indexing And Indexed Assignment,  Up: Indexing Objects

34.3.2 Indexed Assignment Optimization
--------------------------------------

Octave's ubiquitous lazily-copied pass-by-value semantics implies a
problem for performance of user-defined subsasgn methods.  Imagine a
call to subsasgn:

       ss = substruct ("()",{1});
       x = subsasgn (x, ss, 1);

and the corresponding method looking like this:

       function x = subsasgn (x, ss, val)
         ...
         x.myfield (ss.subs{1}) = val;
       endfunction

   The problem is that on entry to the subsasgn method, 'x' is still
referenced from the caller's scope, which means that the method will
first need to unshare (copy) 'x' and 'x.myfield' before performing the
assignment.  Upon completing the call, unless an error occurs, the
result is immediately assigned to 'x' in the caller's scope, so that the
previous value of 'x.myfield' is forgotten.  Hence, the Octave language
implies a copy of N elements (N being the size of 'x.myfield'), where
modifying just a single element would actually suffice, i.e., degrades a
constant-time operation to linear-time one.  This may be a real problem
for user classes that intrinsically store large arrays.

   To partially solve the problem, Octave uses a special optimization
for user-defined subsasgn methods coded as m-files.  When the method
gets called as a result of the built-in assignment syntax (not direct
subsasgn call as shown above), i.e.

       x(1) = 1;

   AND if the subsasgn method is declared with identical input and
output argument, like in the example above, then Octave will ignore the
copy of 'x' inside the caller's scope; therefore, any changes made to
'x' during the method execution will directly affect the caller's copy
as well.  This allows, for instance, defining a polynomial class where
modifying a single element takes constant time.

   It is important to understand the implications that this optimization
brings.  Since no extra copy of 'x' in the caller's scope will exist, it
is _solely_ the callee's responsibility to not leave 'x' in an invalid
state if an error occurs throughout the execution.  Also, if the method
partially changes 'x' and then errors out, the changes _will_ affect 'x'
in the caller's scope.  Deleting or completely replacing 'x' inside
subsasgn will not do anything, however, only indexed assignments matter.

   Since this optimization may change the way code works (especially if
badly written), a built-in variable 'optimize_subsasgn_calls' is
provided to control it.  It is on by default.  Another option to avoid
the effect is to declare subsasgn methods with different output and
input arguments, like this:

       function y = subsasgn (x, ss, val)
         ...
       endfunction


File: octave.info,  Node: Overloading Objects,  Next: Inheritance and Aggregation,  Prev: Indexing Objects,  Up: Object Oriented Programming

34.4 Overloading Objects
========================

* Menu:

* Function Overloading::
* Operator Overloading::
* Precedence of Objects::


File: octave.info,  Node: Function Overloading,  Next: Operator Overloading,  Up: Overloading Objects

34.4.1 Function Overloading
---------------------------

Any Octave function can be overloaded, and allows an object specific
version of this function to be called as needed.  A pertinent example
for our polynomial class might be to overload the 'polyval' function
like

     function [y, dy] = polyval (p, varargin)
       if (nargout == 2)
         [y, dy] = polyval (fliplr (p.poly), varargin{:});
       else
         y = polyval (fliplr (p.poly), varargin{:});
       endif
     endfunction


   This function just hands off the work to the normal Octave 'polyval'
function.  Another interesting example for an overloaded function for
our polynomial class is the 'plot' function.

     function h = plot (p, varargin)
       n = 128;
       rmax = max (abs (roots (p.poly)));
       x = [0 : (n - 1)] / (n - 1) * 2.2 * rmax - 1.1 * rmax;
       if (nargout > 0)
         h = plot (x, p(x), varargin{:});
       else
         plot (x, p(x), varargin{:});
       endif
     endfunction


which allows polynomials to be plotted in the domain near the region of
the roots of the polynomial.

   Functions that are of particular interest to be overloaded are the
class conversion functions such as 'double'.  Overloading these
functions allows the 'cast' function to work with the user class and can
aid in the use of methods of other classes with the user class.  An
example 'double' function for our polynomial class might look like.

     function b = double (a)
       b = a.poly;
     endfunction



File: octave.info,  Node: Operator Overloading,  Next: Precedence of Objects,  Prev: Function Overloading,  Up: Overloading Objects

34.4.2 Operator Overloading
---------------------------

The following table shows, for each built-in numerical operation, the
corresponding function name to use when providing an overloaded method
for a user class.

        Operation      Method         Description
----------------------------------------------------------------------------
        a + b          plus (a, b)    Binary addition
        a - b          minus (a, b)   Binary subtraction operator
        + a            uplus (a)      Unary addition operator
        - a            uminus (a)     Unary subtraction operator
        a .* b         times (a, b)   Element-wise multiplication
                                      operator
        a * b          mtimes (a,     Matrix multiplication
                       b)             operator
        a ./ b         rdivide (a,    Element-wise right division
                       b)             operator
        a / b          mrdivide (a,   Matrix right division
                       b)             operator
        a .\ b         ldivide (a,    Element-wise left division
                       b)             operator
        a \ b          mldivide (a,   Matrix left division
                       b)             operator
        a .^ b         power (a, b)   Element-wise power operator
        a ^ b          mpower (a,     Matrix power operator
                       b)
        a < b          lt (a, b)      Less than operator
        a <= b         le (a, b)      Less than or equal to
                                      operator
        a > b          gt (a, b)      Greater than operator
        a >= b         ge (a, b)      Greater than or equal to
                                      operator
        a == b         eq (a, b)      Equal to operator
        a != b         ne (a, b)      Not equal to operator
        a & b          and (a, b)     Logical and operator
        a | b          or (a, b)      Logical or operator
        !  b           not (a)        Logical not operator
        a'             ctranspose     Complex conjugate transpose
                       (a)            operator
        a.'            transpose      Transpose operator
                       (a)
        a : b          colon (a, b)   Two element range operator
        a : b : c      colon (a, b,   Three element range
                       c)             operator
        [a, b]         horzcat (a,    Horizontal concatenation
                       b)             operator
        [a; b]         vertcat (a,    Vertical concatenation
                       b)             operator
        a(s_1, ...,    subsref (a,    Subscripted reference
        s_n)           s)
        a(s_1, ...,    subsasgn (a,   Subscripted assignment
        s_n) = b       s, b)
        b (a)          subsindex      Convert to zero-based index
                       (a)
        "display"      display (a)    Commandline display
                                      function

Table 34.1: Available overloaded operators and their corresponding class
method

   An example 'mtimes' method for our polynomial class might look like

     function y = mtimes (a, b)
       y = polynomial (conv (double (a), double (b)));
     endfunction



File: octave.info,  Node: Precedence of Objects,  Prev: Operator Overloading,  Up: Overloading Objects

34.4.3 Precedence of Objects
----------------------------

Many functions and operators take two or more arguments and so the case
can easily arise that these functions are called with objects of
different classes.  It is therefore necessary to determine the
precedence of which method of which class to call when there are mixed
objects given to a function or operator.  To do this the 'superiorto'
and 'inferiorto' functions can be used

 -- Built-in Function: superiorto (CLASS_NAME, ...)
     When called from a class constructor, mark the object currently
     constructed as having a higher precedence than CLASS_NAME.  More
     that one such class can be specified in a single call.  This
     function may only be called from a class constructor.

 -- Built-in Function: inferiorto (CLASS_NAME, ...)
     When called from a class constructor, mark the object currently
     constructed as having a lower precedence than CLASS_NAME.  More
     that one such class can be specified in a single call.  This
     function may only be called from a class constructor.

   For example with our polynomial class consider the case

     2 * polynomial ([1, 0, 1]);

That mixes an object of the class "double" with an object of the class
"polynomial".  In this case we like to ensure that the return type of
the above is of the type "polynomial" and so we use the 'superiorto'
function in the class constructor.  In particular our polynomial class
constructor would be modified to be

     ## -*- texinfo -*-
     ## @deftypefn  {Function File} {} polynomial ()
     ## @deftypefnx {Function File} {} polynomial (@var{a})
     ## Create a polynomial object representing the polynomial
     ##
     ## @example
     ## a0 + a1 * x + a2 * x^2 + @dots{} + an * x^n
     ## @end example
     ##
     ## @noindent
     ## from a vector of coefficients [a0 a1 a2 @dots{} an].
     ## @end deftypefn

     function p = polynomial (a)
       if (nargin == 0)
         p.poly = [0];
         p = class (p, "polynomial");
       elseif (nargin == 1)
         if (strcmp (class (a), "polynomial"))
           p = a;
         elseif (isvector (a) && isreal (a))
           p.poly = a(:).';
           p = class (p, "polynomial");
         else
           error ("polynomial: expecting real vector");
         endif
       else
         print_usage ();
       endif
       superiorto ("double");
     endfunction


   Note that user classes always have higher precedence than built-in
Octave types.  So in fact marking our polynomial class higher than the
"double" class is in fact not necessary.

   When faced with two objects that have the same precedence, Octave
will use the method of the object that appears first on the list of
arguments.


File: octave.info,  Node: Inheritance and Aggregation,  Prev: Overloading Objects,  Up: Object Oriented Programming

34.5 Inheritance and Aggregation
================================

Using classes to build new classes is supported by octave through the
use of both inheritance and aggregation.

   Class inheritance is provided by octave using the 'class' function in
the class constructor.  As in the case of the polynomial class, the
octave programmer will create a struct that contains the data fields
required by the class, and then call the class function to indicate that
an object is to be created from the struct.  Creating a child of an
existing object is done by creating an object of the parent class and
providing that object as the third argument of the class function.

   This is easily demonstrated by example.  Suppose the programmer needs
an FIR filter, i.e., a filter with a numerator polynomial but a unity
denominator polynomial.  In traditional octave programming, this would
be performed as follows.

     octave:1> x = [some data vector];
     octave:2> n = [some coefficient vector];
     octave:3> y = filter (n, 1, x);

   The equivalent class could be implemented in a class directory
@FIRfilter that is on the octave path.  The constructor is a file
FIRfilter.m in the class directory.

     ## -*- texinfo -*-
     ## @deftypefn  {Function File} {} FIRfilter ()
     ## @deftypefnx {Function File} {} FIRfilter (@var{p})
     ## Create a FIR filter with polynomial @var{p} as coefficient vector.
     ## @end deftypefn

     function f = FIRfilter (p)

       f.polynomial = [];
       if (nargin == 0)
         p = @polynomial ([1]);
       elseif (nargin == 1)
         if (!isa (p, "polynomial"))
           error ("FIRfilter: expecting polynomial as input argument");
         endif
       else
         print_usage ();
       endif
       f = class (f, "FIRfilter", p);
     endfunction


   As before, the leading comments provide command-line documentation
for the class constructor.  This constructor is very similar to the
polynomial class constructor, except that we pass a polynomial object as
the third argument to the class function, telling octave that the
FIRfilter class will be derived from the polynomial class.  Our FIR
filter does not have any data fields, but we must provide a struct to
the 'class' function.  The 'class' function will add an element named
polynomial to the object struct, so we simply add a dummy element named
polynomial as the first line of the constructor.  This dummy element
will be overwritten by the class function.

   Note further that all our examples provide for the case in which no
arguments are supplied.  This is important since octave will call the
constructor with no arguments when loading objects from save files to
determine the inheritance structure.

   A class may be a child of more than one class (see the documentation
for the 'class' function), and inheritance may be nested.  There is no
limitation to the number of parents or the level of nesting other than
memory or other physical issues.

   As before, we need a 'display' method.  A simple example might be

     function display (f)

       display (f.polynomial);

     endfunction



   Note that we have used the polynomial field of the struct to display
the filter coefficients.

   Once we have the class constructor and display method, we may create
an object by calling the class constructor.  We may also check the class
type and examine the underlying structure.

     octave:1> f = FIRfilter (polynomial ([1 1 1]/3))
     f.polynomial = 0.333333 + 0.333333 * X + 0.333333 * X ^ 2
     octave:2> class (f)
     ans = FIRfilter
     octave:3> isa (f,"FIRfilter")
     ans =  1
     octave:4> isa (f,"polynomial")
     ans =  1
     octave:5> struct (f)
     ans =
     {
     polynomial = 0.333333 + 0.333333 * X + 0.333333 * X ^ 2
     }

   We only need to define a method to actually process data with our
filter and our class is usable.  It is also useful to provide a means of
changing the data stored in the class.  Since the fields in the
underlying struct are private by default, we could provide a mechanism
to access the fields.  The 'subsref' method may be used for both.

     function out = subsref (f, x)
       switch (x.type)
         case "()"
           n = f.polynomial;
           out = filter (n.poly, 1, x.subs{1});
         case "."
           fld = x.subs;
           if (strcmp (fld, "polynomial"))
             out = f.polynomial;
           else
             error ("@FIRfilter/subsref: invalid property \"%s\"", fld);
           endif
         otherwise
           error ("@FIRfilter/subsref: invalid subscript type for FIR filter");
       endswitch
     endfunction


   The "()" case allows us to filter data using the polynomial provided
to the constructor.

     octave:2> f = FIRfilter (polynomial ([1 1 1]/3));
     octave:3> x = ones (5,1);
     octave:4> y = f(x)
     y =

        0.33333
        0.66667
        1.00000
        1.00000
        1.00000

   The "."  case allows us to view the contents of the polynomial field.

     octave:1> f = FIRfilter (polynomial ([1 1 1]/3));
     octave:2> f.polynomial
     ans = 0.333333 + 0.333333 * X + 0.333333 * X ^ 2

   In order to change the contents of the object, we need to define a
'subsasgn' method.  For example, we may make the polynomial field
publicly writable.

     function out = subsasgn (f, index, val)
       switch (index.type)
         case "."
           fld = index.subs;
           if (strcmp (fld, "polynomial"))
             out = f;
             out.polynomial = val;
           else
             error ("@FIRfilter/subsref: invalid property \"%s\"", fld);
           endif
         otherwise
           error ("FIRfilter/subsagn: Invalid index type")
       endswitch
     endfunction


   So that

     octave:6> f = FIRfilter ();
     octave:7> f.polynomial = polynomial ([1 2 3]);
     f.polynomial = 1 + 2 * X + 3 * X ^ 2

   Defining the FIRfilter class as a child of the polynomial class
implies that and FIRfilter object may be used any place that a
polynomial may be used.  This is not a normal use of a filter, so that
aggregation may be a more sensible design approach.  In this case, the
polynomial is simply a field in the class structure.  A class
constructor for this case might be

     ## -*- texinfo -*-
     ## @deftypefn  {Function File} {} FIRfilter ()
     ## @deftypefnx {Function File} {} FIRfilter (@var{p})
     ## Create a FIR filter with polynomial @var{p} as coefficient vector.
     ## @end deftypefn

     function f = FIRfilter (p)

       if (nargin == 0)
         f.polynomial = @polynomial ([1]);
       elseif (nargin == 1)
         if (isa (p, "polynomial"))
           f.polynomial = p;
         else
           error ("FIRfilter: expecting polynomial as input argument");
         endif
       else
         print_usage ();
       endif
       f = class (f, "FIRfilter");
     endfunction


   For our example, the remaining class methods remain unchanged.


File: octave.info,  Node: GUI Development,  Next: System Utilities,  Prev: Object Oriented Programming,  Up: Top

35 GUI Development
******************

Octave is principally a batch or command-line language.  However, it
does offer some limited features for constructing graphical interfaces
for interacting with users.

   The GUI elements available are I/O dialogs and a progress bar.  For
example, rather than hardcoding a filename for output results a script
can open a dialog box and allow the user to choose a file.  Similarly,
if a calculation is expected to take a long time a script can display a
progress bar.

   Several utility functions make it possible to store private data for
use with a GUI which will not pollute the user's variable space.

   Finally, a program written in Octave might want to have long term
storage of preferences or state variables.  This can be done with
user-defined preferences.

* Menu:

* I/O Dialogs::
* Progress Bar::
* GUI Utility Functions::
* User-Defined Preferences::


File: octave.info,  Node: I/O Dialogs,  Next: Progress Bar,  Up: GUI Development

35.1 I/O Dialogs
================

Simple dialog menus are available for choosing directories or files.
They return a string variable which can then be used with any command
requiring a file name.

 -- Function File: DIRNAME = uigetdir ()
 -- Function File: DIRNAME = uigetdir (INIT_PATH)
 -- Function File: DIRNAME = uigetdir (INIT_PATH, DIALOG_NAME)
     Open a GUI dialog for selecting a directory.  If INIT_PATH is not
     given the current working directory is used.  DIALOG_NAME may be
     used to customize the dialog title.

     See also: *note uigetfile: XREFuigetfile, *note uiputfile:
     XREFuiputfile.

 -- Function File: [FNAME, FPATH, FLTIDX] = uigetfile ()
 -- Function File: [...] = uigetfile (FLT)
 -- Function File: [...] = uigetfile (FLT, DIALOG_NAME)
 -- Function File: [...] = uigetfile (FLT, DIALOG_NAME, DEFAULT_FILE)
 -- Function File: [...] = uigetfile (..., "Position", [PX PY])
 -- Function File: [...] = uigetfile (..., "MultiSelect", MODE)

     Open a GUI dialog for selecting a file and return the filename
     FNAME, the path to this file FPATH, and the filter index FLTIDX.
     FLT contains a (list of) file filter string(s) in one of the
     following formats:

     "/path/to/filename.ext"
          If a filename is given then the file extension is extracted
          and used as filter.  In addition, the path is selected as
          current path and the filename is selected as default file.
          Example: 'uigetfile ("myfun.m")'

     A single file extension "*.ext"
          Example: 'uigetfile ("*.ext")'

     A 2-column cell array
          containing a file extension in the first column and a brief
          description in the second column.  Example: 'uigetfile
          ({"*.ext", "My Description";"*.xyz", "XYZ-Format"})'

          The filter string can also contain a semicolon separated list
          of filter extensions.  Example: 'uigetfile
          ({"*.gif;*.png;*.jpg", "Supported Picture Formats"})'

     DIALOG_NAME can be used to customize the dialog title.  If
     DEFAULT_FILE is given then it will be selected in the GUI dialog.
     If, in addition, a path is given it is also used as current path.

     The screen position of the GUI dialog can be set using the
     "Position" key and a 2-element vector containing the pixel
     coordinates.  Two or more files can be selected when setting the
     "MultiSelect" key to "on".  In that case FNAME is a cell array
     containing the files.

     See also: *note uiputfile: XREFuiputfile, *note uigetdir:
     XREFuigetdir.

 -- Function File: [FNAME, FPATH, FLTIDX] = uiputfile ()
 -- Function File: [FNAME, FPATH, FLTIDX] = uiputfile (FLT)
 -- Function File: [FNAME, FPATH, FLTIDX] = uiputfile (FLT, DIALOG_NAME)
 -- Function File: [FNAME, FPATH, FLTIDX] = uiputfile (FLT, DIALOG_NAME,
          DEFAULT_FILE)
     Open a GUI dialog for selecting a file.  FLT contains a (list of)
     file filter string(s) in one of the following formats:

     "/path/to/filename.ext"
          If a filename is given the file extension is extracted and
          used as filter.  In addition the path is selected as current
          path and the filename is selected as default file.  Example:
          'uiputfile ("myfun.m")'

     "*.ext"
          A single file extension.  Example: 'uiputfile ("*.ext")'

     '{"*.ext", "My Description"}'
          A 2-column cell array containing the file extension in the 1st
          column and a brief description in the 2nd column.  Example:
          'uiputfile ({"*.ext","My Description";"*.xyz", "XYZ-Format"})'

     The filter string can also contain a semicolon separated list of
     filter extensions.  Example: 'uiputfile ({"*.gif;*.png;*.jpg",
     "Supported Picture Formats"})'

     DIALOG_NAME can be used to customize the dialog title.  If
     DEFAULT_FILE is given it is preselected in the GUI dialog.  If, in
     addition, a path is given it is also used as current path.

     See also: *note uigetfile: XREFuigetfile, *note uigetdir:
     XREFuigetdir.


File: octave.info,  Node: Progress Bar,  Next: GUI Utility Functions,  Prev: I/O Dialogs,  Up: GUI Development

35.2 Progress Bar
=================

 -- Function File: H = waitbar (FRAC)
 -- Function File: H = waitbar (FRAC, MSG)
 -- Function File: H = waitbar (..., "FigureProperty", "Value", ...)
 -- Function File: waitbar (FRAC)
 -- Function File: waitbar (FRAC, HWBAR)
 -- Function File: waitbar (FRAC, HWBAR, MSG)
     Return a handle H to a new waitbar object.

     The waitbar is filled to fraction FRAC which must be in the range
     [0, 1].  The optional message MSG is centered and displayed above
     the waitbar.  The appearance of the waitbar figure window can be
     configured by passing property/value pairs to the function.

     When called with a single input the current waitbar, if it exists,
     is updated to the new value FRAC.  If there are multiple
     outstanding waitbars they can be updated individually by passing
     the handle HWBAR of the specific waitbar to modify.


File: octave.info,  Node: GUI Utility Functions,  Next: User-Defined Preferences,  Prev: Progress Bar,  Up: GUI Development

35.3 GUI Utility Functions
==========================

These functions do not implement a GUI element but are useful when
developing programs that do.  *Warning:* The functions 'uiwait',
'uiresume', and 'waitfor' are only available for the FLTK tooolkit.

 -- Function File: USED = desktop ("-inuse")
     Return true if the desktop (GUI) is currently in use.

     See also: *note isguirunning: XREFisguirunning.

 -- Function File: DATA = guidata (H)
 -- Function File: guidata (H, DATA)
     Query or set user-custom GUI data.

     The GUI data is stored in the figure handle H.  If H is not a
     figure handle then it's parent figure will be used for storage.

     DATA must be a single object which means it is usually preferable
     for it to be a data container such as a cell array or struct so
     that additional data items can be added easily.

     See also: *note getappdata: XREFgetappdata, *note setappdata:
     XREFsetappdata, *note get: XREFget, *note set: XREFset, *note
     getpref: XREFgetpref, *note setpref: XREFsetpref.

 -- Function File: HDATA = guihandles (H)
 -- Function File: HDATA = guihandles
     Return a structure of object handles for the figure associated with
     handle H.

     If no handle is specified the current figure returned by 'gcf' is
     used.

     The fieldname for each entry of HDATA is taken from the "tag"
     property of the graphic object.  If the tag is empty then the
     handle is not returned.  If there are multiple graphic objects with
     the same tag then the entry in HDATA will be a vector of handles.
     'guihandles' includes all possible handles, including those for
     which "HandleVisibility" is "off".

     See also: *note guidata: XREFguidata, *note findobj: XREFfindobj,
     *note findall: XREFfindall, *note allchild: XREFallchild.

 -- Built-in Function: isguirunning ()
     Return true if Octave is running in GUI mode and false otherwise.

 -- Function File: uiwait
 -- Function File: uiwait (H)
 -- Function File: uiwait (H, TIMEOUT)
     Suspend program execution until the figure with handle H is deleted
     or 'uiresume' is called.  When no figure handle is specified, this
     function uses the current figure.

     If the figure handle is invalid or there is no current figure, this
     functions returns immediately.

     When specified, TIMEOUT defines the number of seconds to wait for
     the figure deletion or the 'uiresume' call.  The timeout value must
     be at least 1.  If a smaller value is specified, a warning is
     issued and a timeout value of 1 is used instead.  If a non-integer
     value is specified, it is truncated towards 0.  If TIMEOUT is not
     specified, the program execution is suspended indefinitely.

     See also: *note uiresume: XREFuiresume, *note waitfor: XREFwaitfor.

 -- Function File: uiresume (H)
     Resume program execution suspended with 'uiwait'.  The handle H
     must be the same as the on specified in 'uiwait'.  If the handle is
     invalid or there is no 'uiwait' call pending for the figure with
     handle H, this function does nothing.

     See also: *note uiwait: XREFuiwait.

 -- Built-in Function: waitfor (H)
 -- Built-in Function: waitfor (H, PROP)
 -- Built-in Function: waitfor (H, PROP, VALUE)
 -- Built-in Function: waitfor (..., "timeout", TIMEOUT)
     Suspend the execution of the current program until a condition is
     satisfied on the graphics handle H.

     While the program is suspended graphics events are still being
     processed normally, allowing callbacks to modify the state of
     graphics objects.  This function is reentrant and can be called
     from a callback, while another 'waitfor' call is pending at the
     top-level.

     In the first form, program execution is suspended until the
     graphics object H is destroyed.  If the graphics handle is invalid,
     the function returns immediately.

     In the second form, execution is suspended until the graphics
     object is destroyed or the property named PROP is modified.  If the
     graphics handle is invalid or the property does not exist, the
     function returns immediately.

     In the third form, execution is suspended until the graphics object
     is destroyed or the property named PROP is set to VALUE.  The
     function 'isequal' is used to compare property values.  If the
     graphics handle is invalid, the property does not exist or the
     property is already set to VALUE, the function returns immediately.

     An optional timeout can be specified using the property 'timeout'.
     This timeout value is the number of seconds to wait for the
     condition to be true.  TIMEOUT must be at least 1.  If a smaller
     value is specified, a warning is issued and a value of 1 is used
     instead.  If the timeout value is not an integer, it is truncated
     towards 0.

     To define a condition on a property named 'timeout', use the string
     '\timeout' instead.

     In all cases, typing CTRL-C stops program execution immediately.

     See also: *note waitforbuttonpress: XREFwaitforbuttonpress, *note
     isequal: XREFisequal.


File: octave.info,  Node: User-Defined Preferences,  Prev: GUI Utility Functions,  Up: GUI Development

35.4 User-Defined Preferences
=============================

 -- Function File: getpref (GROUP, PREF, DEFAULT)
     Return the preference value corresponding to the named preference
     PREF in the preference group GROUP.

     The named preference group must be a character string.

     If PREF does not exist in GROUP and DEFAULT is specified, return
     DEFAULT.

     The preference PREF may be a character string or a cell array of
     character strings.  The corresponding default value DEFAULT may be
     any value, or, if PREF is a cell array of strings, DEFAULT must be
     a cell array of values with the same size as PREF.

     If neither PREF nor DEFAULT are specified, return a structure of
     preferences for the preference group GROUP.

     If no arguments are specified, return a structure containing all
     groups of preferences and their values.

     See also: *note addpref: XREFaddpref, *note setpref: XREFsetpref,
     *note ispref: XREFispref, *note rmpref: XREFrmpref.

 -- Function File: setpref (GROUP, PREF, VAL)
     Set a preference PREF to the given VAL in the named preference
     group GROUP.

     The named preference group must be a character string.

     The preference PREF may be a character string or a cell array of
     character strings.  The corresponding value VAL may be any value,
     or, if PREF is a cell array of strings, VAL must be a cell array of
     values with the same size as PREF.

     If the named preference or group does not exist, it is added.

     See also: *note addpref: XREFaddpref, *note getpref: XREFgetpref,
     *note ispref: XREFispref, *note rmpref: XREFrmpref.

 -- Function File: addpref (GROUP, PREF, VAL)
     Add a preference PREF and associated value VAL to the named
     preference group GROUP.

     The named preference group must be a character string.

     The preference PREF may be a character string or a cell array of
     character strings.  The corresponding value VAL may be any value,
     or, if PREF is a cell array of strings, VAL must be a cell array of
     values with the same size as PREF.

     See also: *note setpref: XREFsetpref, *note getpref: XREFgetpref,
     *note ispref: XREFispref, *note rmpref: XREFrmpref.

 -- Function File: rmpref (GROUP)
 -- Function File: rmpref (GROUP, PREF)
     Remove the named preference PREF from the preference group GROUP.

     The named preference group must be a character string.

     The preference PREF may be a character string or cell array of
     strings.

     If PREF is not specified, remove the preference group GROUP.

     It is an error to remove a nonexistent preference or group.

     See also: *note addpref: XREFaddpref, *note ispref: XREFispref,
     *note setpref: XREFsetpref, *note getpref: XREFgetpref.

 -- Function File: ispref (GROUP, PREF)
     Return true if the named preference PREF exists in the preference
     group GROUP.

     The named preference group must be a character string.

     The preference PREF may be a character string or a cell array of
     character strings.

     If PREF is not specified, return true if the preference group GROUP
     exists.

     See also: *note getpref: XREFgetpref, *note addpref: XREFaddpref,
     *note setpref: XREFsetpref, *note rmpref: XREFrmpref.

 -- Command: prefdir
 -- Command: DIR = prefdir
     Return the directory that contains the preferences for Octave.

     Examples:

     Display the preferences directory

          prefdir

     Change to the preferences folder

          cd (prefdir)

     See also: *note getpref: XREFgetpref, *note setpref: XREFsetpref,
     *note addpref: XREFaddpref, *note rmpref: XREFrmpref, *note ispref:
     XREFispref.

 -- Command: preferences
     Display the GUI preferences dialog window for Octave.


File: octave.info,  Node: System Utilities,  Next: Java Interface,  Prev: GUI Development,  Up: Top

36 System Utilities
*******************

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

* Menu:

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


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

36.1 Timing Utilities
=====================

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

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

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

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

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

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

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

'year'
     Years since 1900.

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

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

'isdst'
     Daylight Savings Time flag.

'zone'
     Time zone.

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

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

     See also: *note strftime: XREFstrftime, *note strptime:
     XREFstrptime, *note localtime: XREFlocaltime, *note gmtime:
     XREFgmtime, *note mktime: XREFmktime, *note now: XREFnow, *note
     date: XREFdate, *note clock: XREFclock, *note datenum: XREFdatenum,
     *note datestr: XREFdatestr, *note datevec: XREFdatevec, *note
     calendar: XREFcalendar, *note weekday: XREFweekday.

 -- Function File: t = now ()
     Return the current local date/time as a serial day number (see
     'datenum').

     The integral part, 'floor (now)' corresponds to the number of days
     between today and Jan 1, 0000.

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

     See also: *note clock: XREFclock, *note date: XREFdate, *note
     datenum: XREFdatenum.

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

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

     See also: *note asctime: XREFasctime, *note time: XREFtime, *note
     localtime: XREFlocaltime.

 -- Built-in Function: TM_STRUCT = gmtime (T)
     Given a value returned from 'time', or any non-negative integer,
     return a time structure corresponding to CUT (Coordinated Universal
     Time).  For example:

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

     See also: *note strftime: XREFstrftime, *note strptime:
     XREFstrptime, *note localtime: XREFlocaltime, *note mktime:
     XREFmktime, *note time: XREFtime, *note now: XREFnow, *note date:
     XREFdate, *note clock: XREFclock, *note datenum: XREFdatenum, *note
     datestr: XREFdatestr, *note datevec: XREFdatevec, *note calendar:
     XREFcalendar, *note weekday: XREFweekday.

 -- Built-in Function: TM_STRUCT = localtime (T)
     Given a value returned from 'time', or any non-negative integer,
     return a time structure corresponding to the local time zone.

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

     See also: *note strftime: XREFstrftime, *note strptime:
     XREFstrptime, *note gmtime: XREFgmtime, *note mktime: XREFmktime,
     *note time: XREFtime, *note now: XREFnow, *note date: XREFdate,
     *note clock: XREFclock, *note datenum: XREFdatenum, *note datestr:
     XREFdatestr, *note datevec: XREFdatevec, *note calendar:
     XREFcalendar, *note weekday: XREFweekday.

 -- Built-in Function: SECONDS = mktime (TM_STRUCT)
     Convert a time structure corresponding to the local time to the
     number of seconds since the epoch.  For example:

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

     See also: *note strftime: XREFstrftime, *note strptime:
     XREFstrptime, *note localtime: XREFlocaltime, *note gmtime:
     XREFgmtime, *note time: XREFtime, *note now: XREFnow, *note date:
     XREFdate, *note clock: XREFclock, *note datenum: XREFdatenum, *note
     datestr: XREFdatestr, *note datevec: XREFdatevec, *note calendar:
     XREFcalendar, *note weekday: XREFweekday.

 -- Function File: asctime (TM_STRUCT)
     Convert a time structure to a string using the following format:
     "ddd mmm mm HH:MM:SS yyyy".  For example:

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

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

     See also: *note ctime: XREFctime, *note localtime: XREFlocaltime,
     *note time: XREFtime.

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

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

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

     Literal character fields:

     '%%'
          % character.

     '%n'
          Newline character.

     '%t'
          Tab character.

     Numeric modifiers (a nonstandard extension):

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

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

     Time fields:

     '%H'
          Hour (00-23).

     '%I'
          Hour (01-12).

     '%k'
          Hour (0-23).

     '%l'
          Hour (1-12).

     '%M'
          Minute (00-59).

     '%p'
          Locale's AM or PM.

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

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

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

     '%S'
          Second (00-61).

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

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

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

     Date fields:

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

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

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

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

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

     '%C'
          Century (00-99).

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

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

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

     '%h'
          Same as %b.

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

     '%m'
          Month (01-12).

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

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

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

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

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

     '%Y'
          Year (1970-).

     See also: *note strptime: XREFstrptime, *note localtime:
     XREFlocaltime, *note gmtime: XREFgmtime, *note mktime: XREFmktime,
     *note time: XREFtime, *note now: XREFnow, *note date: XREFdate,
     *note clock: XREFclock, *note datenum: XREFdatenum, *note datestr:
     XREFdatestr, *note datevec: XREFdatevec, *note calendar:
     XREFcalendar, *note weekday: XREFweekday.

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

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

     See also: *note strftime: XREFstrftime, *note localtime:
     XREFlocaltime, *note gmtime: XREFgmtime, *note mktime: XREFmktime,
     *note time: XREFtime, *note now: XREFnow, *note date: XREFdate,
     *note clock: XREFclock, *note datenum: XREFdatenum, *note datestr:
     XREFdatestr, *note datevec: XREFdatevec, *note calendar:
     XREFcalendar, *note weekday: XREFweekday.

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

 -- Function File: clock ()
     Return the current local date and time as a date vector.  The date
     vector contains the following fields: current year, month (1-12),
     day (1-31), hour (0-23), minute (0-59), and second (0-61).  The
     seconds field has a fractional part after the decimal point for
     extended accuracy.

     For example:

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

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

     See also: *note now: XREFnow, *note date: XREFdate, *note datevec:
     XREFdatevec.

 -- Function File: date ()
     Return the current date as a character string in the form
     DD-MMM-YYYY.

     For example:

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

     See also: *note now: XREFnow, *note clock: XREFclock, *note
     datestr: XREFdatestr, *note localtime: XREFlocaltime.

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

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

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

     See also: *note tic: XREFtic, *note toc: XREFtoc, *note clock:
     XREFclock, *note cputime: XREFcputime, *note addtodate:
     XREFaddtodate.

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

     See also: *note tic: XREFtic, *note toc: XREFtoc.

 -- Function File: is_leap_year ()
 -- Function File: is_leap_year (YEAR)
     Return true if YEAR is a leap year and false otherwise.  If no year
     is specified, 'is_leap_year' uses the current year.  For example:

          is_leap_year (2000)
             => 1

     See also: *note weekday: XREFweekday, *note eomday: XREFeomday,
     *note calendar: XREFcalendar.

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

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

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

     If called with one output argument, 'tic' returns a scalar of type
     'uint64' that may be later passed to 'toc'.

          id = tic; sleep (5); toc (id)
                => 5.0010

     Calling 'tic' and 'toc' this way allows nested timing calls.

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

     See also: *note toc: XREFtoc, *note cputime: XREFcputime.

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

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

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

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

 -- Function File: DAYS = datenum (DATEVEC)
 -- Function File: DAYS = datenum (YEAR, MONTH, DAY)
 -- Function File: DAYS = datenum (YEAR, MONTH, DAY, HOUR)
 -- Function File: DAYS = datenum (YEAR, MONTH, DAY, HOUR, MINUTE)
 -- Function File: DAYS = datenum (YEAR, MONTH, DAY, HOUR, MINUTE,
          SECOND)
 -- Function File: DAYS = datenum ("datestr")
 -- Function File: DAYS = datenum ("datestr", P)
 -- Function File: [DAYS, SECS] = datenum (...)
     Return the date/time input as a serial day number, with Jan 1, 0000
     defined as day 1.

     The integer part, 'floor (DAYS)' counts the number of complete days
     in the date input.

     The fractional part, 'rem (DAYS, 1)' corresponds to the time on the
     given day.

     The input may be a date vector (see 'datevec'), datestr (see
     'datestr'), or directly specified as input.

     When processing input datestrings, P is the year at the start of
     the century to which two-digit years will be referenced.  If not
     specified, it defaults to the current year minus 50.

     The optional output SECS holds the time on the specified day with
     greater precision than DAYS.

     Notes:

        * Years can be negative and/or fractional.

        * Months below 1 are considered to be January.

        * Days of the month start at 1.

        * Days beyond the end of the month go into subsequent months.

        * Days before the beginning of the month go to the previous
          month.

        * Days can be fractional.

     *Caution:* this function does not attempt to handle Julian
     calendars so dates before October 15, 1582 are wrong by as much as
     eleven days.  Also, be aware that only Roman Catholic countries
     adopted the calendar in 1582.  It took until 1924 for it to be
     adopted everywhere.  See the Wikipedia entry on the Gregorian
     calendar for more details.

     *Warning:* leap seconds are ignored.  A table of leap seconds is
     available on the Wikipedia entry for leap seconds.

     See also: *note datestr: XREFdatestr, *note datevec: XREFdatevec,
     *note now: XREFnow, *note clock: XREFclock, *note date: XREFdate.

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

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

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

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

     Code    Format                           Example
     -------------------------------------------------------------------
     0       dd-mmm-yyyy HH:MM:SS             07-Sep-2000 15:38:09
     1       dd-mmm-yyyy                      07-Sep-2000
     2       mm/dd/yy                         09/07/00
     3       mmm                              Sep
     4       m                                S
     5       mm                               09
     6       mm/dd                            09/07
     7       dd                               07
     8       ddd                              Thu
     9       d                                T
     10      yyyy                             2000
     11      yy                               00
     12      mmmyy                            Sep00
     13      HH:MM:SS                         15:38:09
     14      HH:MM:SS PM                      03:38:09 PM
     15      HH:MM                            15:38
     16      HH:MM PM                         03:38 PM
     17      QQ-YY                            Q3-00
     18      QQ                               Q3
     19      dd/mm                            07/09
     20      dd/mm/yy                         07/09/00
     21      mmm.dd,yyyy HH:MM:SS             Sep.07,2000 15:38:08
     22      mmm.dd,yyyy                      Sep.07,2000
     23      mm/dd/yyyy                       09/07/2000
     24      dd/mm/yyyy                       07/09/2000
     25      yy/mm/dd                         00/09/07
     26      yyyy/mm/dd                       2000/09/07
     27      QQ-YYYY                          Q3-2000
     28      mmmyyyy                          Sep2000
     29      yyyy-mm-dd                       2000-09-07
     30      yyyymmddTHHMMSS                  20000907T153808
     31      yyyy-mm-dd HH:MM:SS              2000-09-07 15:38:08

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

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

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

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

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

     See also: *note datenum: XREFdatenum, *note datevec: XREFdatevec,
     *note date: XREFdate, *note now: XREFnow, *note clock: XREFclock.

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

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

     F is the format string used to interpret date strings (see
     'datestr').  If DATE is a string, but no format is specified, then
     a relatively slow search is performed through various formats.  It
     is always preferable to specify the format string F if it is known.
     Formats which do not specify a particular time component will have
     the value set to zero.  Formats which do not specify a date will
     default to January 1st of the current year.

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

     See also: *note datenum: XREFdatenum, *note datestr: XREFdatestr,
     *note clock: XREFclock, *note now: XREFnow, *note date: XREFdate.

 -- Function File: D = addtodate (D, Q, F)
     Add Q amount of time (with units F) to the serial datenum, D.

     F must be one of "year", "month", "day", "hour", "minute",
     "second", or "millisecond".

     See also: *note datenum: XREFdatenum, *note datevec: XREFdatevec,
     *note etime: XREFetime.

 -- Function File: C = calendar ()
 -- Function File: C = calendar (D)
 -- Function File: C = calendar (Y, M)
 -- Function File: calendar (...)
     Return the current monthly calendar in a 6x7 matrix.

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

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

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

     See also: *note datenum: XREFdatenum, *note datestr: XREFdatestr.

 -- Function File: [N, S] = weekday (D)
 -- Function File: [N, S] = weekday (D, FORMAT)
     Return the day of the week as a number in N and as a string in S.
     The days of the week are numbered 1-7 with the first day being
     Sunday.

     D is a serial date number or a date string.

     If the string FORMAT is not present or is equal to "short" then S
     will contain the abbreviated name of the weekday.  If FORMAT is
     "long" then S will contain the full name.

     Table of return values based on FORMAT:

     N    "short"   "long"
     ----------------------------
     1    Sun       Sunday
     2    Mon       Monday
     3    Tue       Tuesday
     4    Wed       Wednesday
     5    Thu       Thursday
     6    Fri       Friday
     7    Sat       Saturday

     See also: *note eomday: XREFeomday, *note is_leap_year:
     XREFis_leap_year, *note calendar: XREFcalendar, *note datenum:
     XREFdatenum, *note datevec: XREFdatevec.

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

     See also: *note weekday: XREFweekday, *note datenum: XREFdatenum,
     *note datevec: XREFdatevec, *note is_leap_year: XREFis_leap_year,
     *note calendar: XREFcalendar.

 -- Function File: datetick ()
 -- Function File: datetick (FORM)
 -- Function File: datetick (AXIS, FORM)
 -- Function File: datetick (..., "keeplimits")
 -- Function File: datetick (..., "keepticks")
 -- Function File: datetick (HAX, ...)
     Add date formatted tick labels to an axis.  The axis to apply the
     ticks to is determined by AXIS which can take the values "x", "y",
     or "z".  The default value is "x".  The formatting of the labels is
     determined by the variable FORM, which can either be a string or
     positive integer that 'datestr' accepts.

     See also: *note datenum: XREFdatenum, *note datestr: XREFdatestr.


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

36.2 Filesystem Utilities
=========================

Octave includes many utility functions for copying, moving, renaming,
and deleting files; for creating, reading, and deleting directories; for
retrieving status information on files; and for manipulating file and
path names.

 -- Function File: movefile (F1)
 -- Function File: movefile (F1, F2)
 -- Function File: movefile (F1, F2, 'f')
 -- Function File: [STATUS, MSG, MSGID] = movefile (...)
     Move the file F1 to the destination F2.

     The name F1 may contain globbing patterns.  If F1 expands to
     multiple file names, F2 must be a directory.  If no destination F2
     is specified then the destination is the present working directory.
     If F2 is a file name then F1 is renamed to F2.  When the force flag
     'f' is given any existing files will be overwritten without
     prompting.

     If successful, STATUS is 1, and MSG, MSGID are empty character
     strings ("").  Otherwise, STATUS is 0, MSG contains a
     system-dependent error message, and MSGID contains a unique message
     identifier.  Note that the status code is exactly opposite that of
     the 'system' command.

     See also: *note rename: XREFrename, *note copyfile: XREFcopyfile,
     *note unlink: XREFunlink, *note delete: XREFdelete, *note glob:
     XREFglob.

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

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

     See also: *note movefile: XREFmovefile, *note copyfile:
     XREFcopyfile, *note ls: XREFls, *note dir: XREFdir.

 -- Function File: [STATUS, MSG, MSGID] = copyfile (F1, F2)
 -- Function File: [STATUS, MSG, MSGID] = copyfile (F1, F2, 'f')
     Copy the file F1 to the destination F2.

     The name F1 may contain globbing patterns.  If F1 expands to
     multiple file names, F2 must be a directory.  when the force flag
     'f' is given any existing files will be overwritten without
     prompting.

     If successful, STATUS is 1, and MSG, MSGID are empty character
     strings ("").  Otherwise, STATUS is 0, MSG contains a
     system-dependent error message, and MSGID contains a unique message
     identifier.  Note that the status code is exactly opposite that of
     the 'system' command.

     See also: *note movefile: XREFmovefile, *note rename: XREFrename,
     *note unlink: XREFunlink, *note delete: XREFdelete, *note glob:
     XREFglob.

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

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

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

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

     See also: *note symlink: XREFsymlink, *note unlink: XREFunlink,
     *note readlink: XREFreadlink, *note lstat: XREFlstat.

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

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

     See also: *note link: XREFlink, *note unlink: XREFunlink, *note
     readlink: XREFreadlink, *note lstat: XREFlstat.

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

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

     See also: *note lstat: XREFlstat, *note symlink: XREFsymlink, *note
     link: XREFlink, *note unlink: XREFunlink, *note delete: XREFdelete.

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

     If no PARENT directory is specified the present working directory
     is used.

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

     See also: *note rmdir: XREFrmdir, *note pwd: XREFpwd, *note cd:
     XREFcd.

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

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

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

     See also: *note mkdir: XREFmkdir, *note confirm_recursive_rmdir:
     XREFconfirm_recursive_rmdir, *note pwd: XREFpwd.

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

     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.

     See also: *note rmdir: XREFrmdir.

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

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

     See also: *note pipe: XREFpipe.

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

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

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

     'ino'
          File number of the file.

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

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

     'nlink'
          Number of links.

     'uid'
          User ID of file's owner.

     'gid'
          Group ID of file's group.

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

     'size'
          Size in bytes.

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

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

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

     'blksize'
          Size of blocks in the file.

     'blocks'
          Number of blocks allocated for file.

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

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

     For example:

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

     See also: *note lstat: XREFlstat, *note ls: XREFls, *note dir:
     XREFdir.

 -- Built-in Function: S_ISBLK (MODE)
     Return true if MODE corresponds to a block device.

     The value of MODE is assumed to be returned from a call to 'stat'.

     See also: *note stat: XREFstat, *note lstat: XREFlstat.

 -- Built-in Function: S_ISCHR (MODE)
     Return true if MODE corresponds to a character device.

     The value of MODE is assumed to be returned from a call to 'stat'.

     See also: *note stat: XREFstat, *note lstat: XREFlstat.

 -- Built-in Function: S_ISDIR (MODE)
     Return true if MODE corresponds to a directory.

     The value of MODE is assumed to be returned from a call to 'stat'.

     See also: *note stat: XREFstat, *note lstat: XREFlstat.

 -- Built-in Function: S_ISFIFO (MODE)
     Return true if MODE corresponds to a fifo.

     The value of MODE is assumed to be returned from a call to 'stat'.

     See also: *note stat: XREFstat, *note lstat: XREFlstat.

 -- Built-in Function: S_ISLNK (MODE)
     Return true if MODE corresponds to a symbolic link.

     The value of MODE is assumed to be returned from a call to 'stat'.

     See also: *note stat: XREFstat, *note lstat: XREFlstat.

 -- Built-in Function: S_ISREG (MODE)
     Return true if MODE corresponds to a regular file.

     The value of MODE is assumed to be returned from a call to 'stat'.

     See also: *note stat: XREFstat, *note lstat: XREFlstat.

 -- Built-in Function: S_ISSOCK (MODE)
     Return true if MODE corresponds to a socket.

     The value of MODE is assumed to be returned from a call to 'stat'.

     See also: *note stat: XREFstat, *note lstat: XREFlstat.

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

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

     'Name'
          Full name of FILE.

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

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

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

     'directory'
          True if FILE is a directory.

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

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

     'UserExecute'
     'GroupExecute'
     'OtherExecute'
          True if the user (group; other users) has execute permission
          for FILE.

     If an attribute does not apply (i.e., archive on a Unix system)
     then the field is set to NaN.

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

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

     See also: *note glob: XREFglob.

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

     See also: *note exist: XREFexist, *note stat: XREFstat, *note
     is_absolute_filename: XREFis_absolute_filename, *note
     is_rooted_relative_filename: XREFis_rooted_relative_filename.

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

     If an error occurs, return an empty cell array in FILES.  If
     successful, ERR is 0 and MSG is an empty string.  Otherwise, ERR is
     nonzero and MSG contains a system-dependent error message.

     See also: *note ls: XREFls, *note dir: XREFdir, *note glob:
     XREFglob, *note what: XREFwhat.

 -- Built-in Function: glob (PATTERN)
     Given an array of pattern strings (as a char array or a cell array)
     in PATTERN, return a cell array of file names that match any of
     them, or an empty cell array if no patterns match.  The pattern
     strings are interpreted as filename globbing patterns (as they are
     used by Unix shells).  Within a pattern

     '*'
          matches any string, including the null string,

     '?'
          matches any single character, and

     '[...]'
          matches any of the enclosed characters.

     Tilde expansion is performed on each of the patterns before looking
     for matching file names.  For example:

          ls
             =>
                file1  file2  file3  myfile1 myfile1b
          glob ("*file1")
             =>
                {
                  [1,1] = file1
                  [2,1] = myfile1
                }
          glob ("myfile?")
             =>
                {
                  [1,1] = myfile1
                }
          glob ("file[12]")
             =>
                {
                  [1,1] = file1
                  [2,1] = file2
                }

     See also: *note ls: XREFls, *note dir: XREFdir, *note readdir:
     XREFreaddir, *note what: XREFwhat, *note fnmatch: XREFfnmatch.

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

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

     See also: *note glob: XREFglob, *note regexp: XREFregexp.

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

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

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

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

     See also: *note file_in_loadpath: XREFfile_in_loadpath, *note
     find_dir_in_path: XREFfind_dir_in_path, *note path: XREFpath.

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

     If "all" is given, the function returns all valid file separators
     in the form of a string.  The list of file separators is
     system-dependent.  It is '/' (forward slash) under UNIX or
     Mac OS X, '/' and '\' (forward and backward slashes) under Windows.

     See also: *note pathsep: XREFpathsep.

 -- Built-in Function: VAL = filemarker ()
 -- Built-in Function: filemarker (NEW_VAL)
 -- Built-in Function: filemarker (NEW_VAL, "local")
     Query or set the character used to separate filename from the the
     subfunction names contained within the file.  This can be used in a
     generic manner to interact with subfunctions.  For example,

          help (["myfunc", filemarker, "mysubfunc"])

     returns the help string associated with the subfunction 'mysubfunc'
     of the function 'myfunc'.  Another use of 'filemarker' is when
     debugging it allows easier placement of breakpoints within
     subfunctions.  For example,

          dbstop (["myfunc", filemarker, "mysubfunc"])

     will set a breakpoint at the first line of the subfunction
     'mysubfunc'.

     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.

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

     See also: *note fullfile: XREFfullfile.

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

     See also: *note fileparts: XREFfileparts.

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

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

 -- Built-in Function: [CNAME, STATUS, MSG] = canonicalize_file_name
          (FNAME)
     Return the canonical name of file FNAME.  If the file does not
     exist the empty string ("") is returned.

     See also: *note make_absolute_filename: XREFmake_absolute_filename,
     *note is_absolute_filename: XREFis_absolute_filename, *note
     is_rooted_relative_filename: XREFis_rooted_relative_filename.

 -- Built-in Function: make_absolute_filename (FILE)
     Return the full name of FILE beginning from the root of the file
     system.  No check is done for the existence of FILE.

     See also: *note canonicalize_file_name: XREFcanonicalize_file_name,
     *note is_absolute_filename: XREFis_absolute_filename, *note
     is_rooted_relative_filename: XREFis_rooted_relative_filename, *note
     isdir: XREFisdir.

 -- Built-in Function: is_absolute_filename (FILE)
     Return true if FILE is an absolute filename.

     See also: *note is_rooted_relative_filename:
     XREFis_rooted_relative_filename, *note make_absolute_filename:
     XREFmake_absolute_filename, *note isdir: XREFisdir.

 -- Built-in Function: is_rooted_relative_filename (FILE)
     Return true if FILE is a rooted-relative filename.

     See also: *note is_absolute_filename: XREFis_absolute_filename,
     *note make_absolute_filename: XREFmake_absolute_filename, *note
     isdir: XREFisdir.

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

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

 -- Function File: tempname ()
 -- Function File: tempname (DIR)
 -- Function File: tempname (DIR, PREFIX)
     This function is an alias for 'tmpnam'.

     See also: *note tmpnam: XREFtmpnam.

 -- Function File: CURRENT_STATE = recycle ()
 -- Function File: OLD_STATE = recycle (NEW_STATE)
     Query or set the preference for recycling deleted files.

     Recycling files, instead of permanently deleting them, is not
     currently implemented in Octave.  To help avoid accidental data
     loss an error will be raised if an attempt is made to enable file
     recycling.

     See also: *note delete: XREFdelete.


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

36.3 File Archiving Utilities
=============================

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

     See also: *note bzip2: XREFbzip2, *note unpack: XREFunpack, *note
     gunzip: XREFgunzip, *note unzip: XREFunzip, *note untar: XREFuntar.

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

     See also: *note gunzip: XREFgunzip, *note bzip2: XREFbzip2, *note
     zip: XREFzip, *note tar: XREFtar.

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

     See also: *note gzip: XREFgzip, *note unpack: XREFunpack, *note
     bunzip2: XREFbunzip2, *note unzip: XREFunzip, *note untar:
     XREFuntar.

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

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

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

     See also: *note untar: XREFuntar, *note bzip2: XREFbzip2, *note
     gzip: XREFgzip, *note zip: XREFzip.

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

     See also: *note tar: XREFtar, *note unpack: XREFunpack, *note
     bunzip2: XREFbunzip2, *note gunzip: XREFgunzip, *note unzip:
     XREFunzip.

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

     See also: *note unzip: XREFunzip, *note bzip2: XREFbzip2, *note
     gzip: XREFgzip, *note tar: XREFtar.

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

     See also: *note zip: XREFzip, *note unpack: XREFunpack, *note
     bunzip2: XREFbunzip2, *note gunzip: XREFgunzip, *note untar:
     XREFuntar.

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

     The optional return value is a list of FILES unpacked.

     See also: *note bzip2: XREFbzip2, *note gzip: XREFgzip, *note zip:
     XREFzip, *note tar: XREFtar.

 -- Function File: ENTRIES = bzip2 (FILES)
 -- Function File: ENTRIES = bzip2 (FILES, OUTDIR)
     Compress the list of files specified in FILES.  Each file is
     compressed separately and a new file with a '".bz2"' extension is
     created.  The original files are not modified.  Existing compressed
     files are silently overwritten.  If OUTDIR is defined the
     compressed files are placed in this directory.

     See also: *note bunzip2: XREFbunzip2, *note gzip: XREFgzip, *note
     zip: XREFzip, *note tar: XREFtar.


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

36.4 Networking Utilities
=========================

* Menu:

* FTP Objects::
* URL Manipulation::
* Base64 and Binary Data Transmission::

 -- Built-in Function: gethostname ()
     Return the hostname of the system where Octave is running.


File: octave.info,  Node: FTP Objects,  Next: URL Manipulation,  Up: Networking Utilities

36.4.1 FTP Objects
------------------

Octave supports the FTP protocol through an object-oriented interface.
Use the function 'ftp' to create an FTP object which represents the
connection.  All FTP functions take an FTP object as the first argument.

 -- Function File: F = ftp (HOST)
 -- Function File: F = ftp (HOST, USERNAME, PASSWORD)
     Connect to the FTP server HOST with USERNAME and PASSWORD.  If
     USERNAME and PASSWORD are not specified, user "anonymous" with no
     password is used.  The returned FTP object F represents the
     established FTP connection.

     The list of actions for an FTP object are shown below.  All
     functions require an FTP object as the first argument.

     Method      Description
     -----------------------------------------------------------------------
     ascii       Set transfer type to ascii
     binary      Set transfer type to binary
     cd          Change remote working directory
     close       Close FTP connection
     delete      Delete remote file
     dir         List remote directory contents
     mget        Download remote files
     mkdir       Create remote directory
     mput        Upload local files
     rename      Rename remote file or directory
     rmdir       Remove remote directory

 -- Function File: close (F)
     Close the FTP connection represented by the FTP object F.

     F is an FTP object returned by the 'ftp' function.

 -- Function File: mget (F, FILE)
 -- Function File: mget (F, DIR)
 -- Function File: mget (F, REMOTE_NAME, TARGET)
     Download a remote file FILE or directory DIR to the local directory
     on the FTP connection F.  F is an FTP object returned by the 'ftp'
     function.

     The arguments FILE and DIR can include wildcards and any files or
     directories on the remote server that match will be downloaded.

     If a third argument TARGET is given, then a single file or
     directory will be downloaded to the local directory and the local
     name will be changed to TARGET.

 -- Function File: mput (F, FILE)
     Upload the local file FILE into the current remote directory on the
     FTP connection F.  F is an FTP object returned by the ftp function.

     The argument FILE is passed through the 'glob' function and any
     files that match the wildcards in FILE will be uploaded.

 -- Function File: cd (F)
 -- Function File: cd (F, PATH)
     Get or set the remote directory on the FTP connection F.

     F is an FTP object returned by the 'ftp' function.

     If PATH is not specified, return the remote current working
     directory.  Otherwise, set the remote directory to PATH and return
     the new remote working directory.

     If the directory does not exist, an error message is printed and
     the working directory is not changed.

 -- Function File: LST = dir (F)
     List the current directory in verbose form for the FTP connection
     F.

     F is an FTP object returned by the 'ftp' function.

 -- Function File: ascii (F)
     Set the FTP connection F to use ASCII mode for transfers.  ASCII
     mode is only appropriate for text files as it will convert the
     remote host's newline representation to the local host's newline
     representation.

     F is an FTP object returned by the 'ftp' function.

 -- Function File: binary (F)
     Set the FTP connection F to use binary mode for transfers.  In
     binary mode there is no conversion of newlines from the remote
     representation to the local representation.

     F is an FTP object returned by the 'ftp' function.

 -- Function File: delete (F, FILE)
     Delete the remote file FILE over the FTP connection F.

     F is an FTP object returned by the 'ftp' function.

 -- Function File: rename (F, OLDNAME, NEWNAME)
     Rename or move the remote file or directory OLDNAME to NEWNAME,
     over the FTP connection F.

     F is an FTP object returned by the ftp function.

 -- Function File: mkdir (F, PATH)
     Create the remote directory PATH, over the FTP connection F.

     F is an FTP object returned by the 'ftp' function.

 -- Function File: rmdir (F, PATH)
     Remove the remote directory PATH, over the FTP connection F.

     F is an FTP object returned by the 'ftp' function.


File: octave.info,  Node: URL Manipulation,  Next: Base64 and Binary Data Transmission,  Prev: FTP Objects,  Up: Networking Utilities

36.4.2 URL Manipulation
-----------------------

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

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

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

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

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

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

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

     See also: *note urlwrite: XREFurlwrite.

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

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

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

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

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

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

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

     See also: *note urlread: XREFurlread.


File: octave.info,  Node: Base64 and Binary Data Transmission,  Prev: URL Manipulation,  Up: Networking Utilities

36.4.3 Base64 and Binary Data Transmission
------------------------------------------

Some transmission channels can not accept binary data.  It is customary
to encode binary data in Base64 for transmission and to decode the data
upon reception.

 -- Built-in Function: S = base64_encode (X)
     Encode a double matrix or array X into the base64 format string S.

     See also: *note base64_decode: XREFbase64_decode.

 -- Built-in Function: X = base64_decode (S)
 -- Built-in Function: X = base64_decode (S, DIMS)
     Decode the double matrix or array X from the base64 encoded string
     S.  The optional input parameter DIMS should be a vector containing
     the dimensions of the decoded array.

     See also: *note base64_encode: XREFbase64_encode.


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

36.5 Controlling Subprocesses
=============================

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

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

 -- Built-in Function: system ("STRING")
 -- Built-in Function: system ("STRING", RETURN_OUTPUT)
 -- Built-in Function: system ("STRING", RETURN_OUTPUT, TYPE)
 -- Built-in Function: [STATUS, OUTPUT] = system (...)
     Execute a shell command specified by STRING.  If the optional
     argument TYPE is "async", the process is started in the background
     and the process ID of the child process is returned immediately.
     Otherwise, the child process is started and Octave waits until it
     exits.  If the TYPE argument is omitted, it defaults to the value
     "sync".

     If SYSTEM is called with one or more output arguments, or if the
     optional argument RETURN_OUTPUT is true and the subprocess is
     started synchronously, then the output from the command is returned
     as a variable.  Otherwise, if the subprocess is executed
     synchronously, its output is sent to the standard output.  To send
     the output of a command executed with 'system' through the pager,
     use a command like

          [output, text] = system ("cmd");
          disp (text);

     or

          printf ("%s\n", nthargout (2, "system", "cmd"));

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

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

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

     For commands run asynchronously, STATUS is the process id of the
     command shell that is started to run the command.

     See also: *note unix: XREFunix, *note dos: XREFdos.

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

     See also: *note dos: XREFdos, *note system: XREFsystem, *note
     isunix: XREFisunix, *note ispc: XREFispc.

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

     See also: *note unix: XREFunix, *note system: XREFsystem, *note
     isunix: XREFisunix, *note ispc: XREFispc.

 -- Function File: OUTPUT = perl (SCRIPTFILE)
 -- Function File: OUTPUT = perl (SCRIPTFILE, ARGUMENT1, ARGUMENT2, ...)
 -- Function File: [OUTPUT, STATUS] = perl (...)
     Invoke Perl script SCRIPTFILE, possibly with a list of command line
     arguments.  Return output in OUTPUT and optional status in STATUS.
     If SCRIPTFILE is not an absolute file name it is is searched for in
     the current directory and then in the Octave loadpath.

     See also: *note system: XREFsystem, *note python: XREFpython.

 -- Function File: OUTPUT = python (SCRIPTFILE)
 -- Function File: OUTPUT = python (SCRIPTFILE, ARGUMENT1, ARGUMENT2,
          ...)
 -- Function File: [OUTPUT, STATUS] = python (...)
     Invoke Python script SCRIPTFILE, possibly with a list of command
     line arguments.  Return output in OUTPUT and optional status in
     STATUS.  If SCRIPTFILE is not an absolute file name it is is
     searched for in the current directory and then in the Octave
     loadpath.

     See also: *note system: XREFsystem, *note perl: XREFperl.

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

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

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

     For example:

          fid = popen ("ls -ltr / | tail -3", "r");
          while (ischar (s = fgets (fid)))
            fputs (stdout, s);
          endwhile

             -| drwxr-xr-x  33 root  root  3072 Feb 15 13:28 etc
             -| drwxr-xr-x   3 root  root  1024 Feb 15 13:28 lib
             -| drwxrwxrwt  15 root  root  2048 Feb 17 14:53 tmp

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

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

     For example:

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

             -| these
             -| strings
             -| some
             -| are

     Note that 'popen2', unlike 'popen', will not "reap" the child
     process.  If you don't use 'waitpid' to check the child's exit
     status, it will linger until Octave exits.

     See also: *note popen: XREFpopen, *note waitpid: XREFwaitpid.

 -- Built-in Function: VAL = EXEC_PATH ()
 -- Built-in Function: OLD_VAL = EXEC_PATH (NEW_VAL)
 -- Built-in Function: EXEC_PATH (NEW_VAL, "local")
     Query or set the internal variable that specifies a colon separated
     list of directories to append to the shell PATH when executing
     external programs.  The initial value of is taken from the
     environment variable 'OCTAVE_EXEC_PATH', but that value can be
     overridden by the command line argument '--exec-path PATH'.

     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.

     See also: *note IMAGE_PATH: XREFIMAGE_PATH, *note OCTAVE_HOME:
     XREFOCTAVE_HOME.

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

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

     Fork can return one of the following values:

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

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

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

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

          exec ("ls" "-l")

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

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

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

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

     See also: *note mkfifo: XREFmkfifo.

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

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

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

     -1
          Wait for any child process.

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

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

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

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

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

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

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

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

     See also: *note WCONTINUE: XREFWCONTINUE, *note WCOREDUMP:
     XREFWCOREDUMP, *note WEXITSTATUS: XREFWEXITSTATUS, *note
     WIFCONTINUED: XREFWIFCONTINUED, *note WIFSIGNALED: XREFWIFSIGNALED,
     *note WIFSTOPPED: XREFWIFSTOPPED, *note WNOHANG: XREFWNOHANG, *note
     WSTOPSIG: XREFWSTOPSIG, *note WTERMSIG: XREFWTERMSIG, *note
     WUNTRACED: XREFWUNTRACED.

 -- Built-in Function: WCONTINUE ()
     Return the numerical value of the option argument that may be
     passed to 'waitpid' to indicate that it should also return if a
     stopped child has been resumed by delivery of a 'SIGCONT' signal.

     See also: *note waitpid: XREFwaitpid, *note WNOHANG: XREFWNOHANG,
     *note WUNTRACED: XREFWUNTRACED.

 -- Built-in Function: WCOREDUMP (STATUS)
     Given STATUS from a call to 'waitpid', return true if the child
     produced a core dump.  This function should only be employed if
     'WIFSIGNALED' returned true.  The macro used to implement this
     function is not specified in POSIX.1-2001 and is not available on
     some Unix implementations (e.g., AIX, SunOS).

     See also: *note waitpid: XREFwaitpid, *note WIFEXITED:
     XREFWIFEXITED, *note WEXITSTATUS: XREFWEXITSTATUS, *note
     WIFSIGNALED: XREFWIFSIGNALED, *note WTERMSIG: XREFWTERMSIG, *note
     WIFSTOPPED: XREFWIFSTOPPED, *note WSTOPSIG: XREFWSTOPSIG, *note
     WIFCONTINUED: XREFWIFCONTINUED.

 -- Built-in Function: WEXITSTATUS (STATUS)
     Given STATUS from a call to 'waitpid', return the exit status of
     the child.  This function should only be employed if 'WIFEXITED'
     returned true.

     See also: *note waitpid: XREFwaitpid, *note WIFEXITED:
     XREFWIFEXITED, *note WIFSIGNALED: XREFWIFSIGNALED, *note WTERMSIG:
     XREFWTERMSIG, *note WCOREDUMP: XREFWCOREDUMP, *note WIFSTOPPED:
     XREFWIFSTOPPED, *note WSTOPSIG: XREFWSTOPSIG, *note WIFCONTINUED:
     XREFWIFCONTINUED.

 -- Built-in Function: WIFCONTINUED (STATUS)
     Given STATUS from a call to 'waitpid', return true if the child
     process was resumed by delivery of 'SIGCONT'.

     See also: *note waitpid: XREFwaitpid, *note WIFEXITED:
     XREFWIFEXITED, *note WEXITSTATUS: XREFWEXITSTATUS, *note
     WIFSIGNALED: XREFWIFSIGNALED, *note WTERMSIG: XREFWTERMSIG, *note
     WCOREDUMP: XREFWCOREDUMP, *note WIFSTOPPED: XREFWIFSTOPPED, *note
     WSTOPSIG: XREFWSTOPSIG.

 -- Built-in Function: WIFSIGNALED (STATUS)
     Given STATUS from a call to 'waitpid', return true if the child
     process was terminated by a signal.

     See also: *note waitpid: XREFwaitpid, *note WIFEXITED:
     XREFWIFEXITED, *note WEXITSTATUS: XREFWEXITSTATUS, *note WTERMSIG:
     XREFWTERMSIG, *note WCOREDUMP: XREFWCOREDUMP, *note WIFSTOPPED:
     XREFWIFSTOPPED, *note WSTOPSIG: XREFWSTOPSIG, *note WIFCONTINUED:
     XREFWIFCONTINUED.

 -- Built-in Function: WIFSTOPPED (STATUS)
     Given STATUS from a call to 'waitpid', return true if the child
     process was stopped by delivery of a signal; this is only possible
     if the call was done using 'WUNTRACED' or when the child is being
     traced (see ptrace(2)).

     See also: *note waitpid: XREFwaitpid, *note WIFEXITED:
     XREFWIFEXITED, *note WEXITSTATUS: XREFWEXITSTATUS, *note
     WIFSIGNALED: XREFWIFSIGNALED, *note WTERMSIG: XREFWTERMSIG, *note
     WCOREDUMP: XREFWCOREDUMP, *note WSTOPSIG: XREFWSTOPSIG, *note
     WIFCONTINUED: XREFWIFCONTINUED.

 -- Built-in Function: WIFEXITED (STATUS)
     Given STATUS from a call to 'waitpid', return true if the child
     terminated normally.

     See also: *note waitpid: XREFwaitpid, *note WEXITSTATUS:
     XREFWEXITSTATUS, *note WIFSIGNALED: XREFWIFSIGNALED, *note
     WTERMSIG: XREFWTERMSIG, *note WCOREDUMP: XREFWCOREDUMP, *note
     WIFSTOPPED: XREFWIFSTOPPED, *note WSTOPSIG: XREFWSTOPSIG, *note
     WIFCONTINUED: XREFWIFCONTINUED.

 -- Built-in Function: WNOHANG ()
     Return the numerical value of the option argument that may be
     passed to 'waitpid' to indicate that it should return its status
     immediately instead of waiting for a process to exit.

     See also: *note waitpid: XREFwaitpid, *note WUNTRACED:
     XREFWUNTRACED, *note WCONTINUE: XREFWCONTINUE.

 -- Built-in Function: WSTOPSIG (STATUS)
     Given STATUS from a call to 'waitpid', return the number of the
     signal which caused the child to stop.  This function should only
     be employed if 'WIFSTOPPED' returned true.

     See also: *note waitpid: XREFwaitpid, *note WIFEXITED:
     XREFWIFEXITED, *note WEXITSTATUS: XREFWEXITSTATUS, *note
     WIFSIGNALED: XREFWIFSIGNALED, *note WTERMSIG: XREFWTERMSIG, *note
     WCOREDUMP: XREFWCOREDUMP, *note WIFSTOPPED: XREFWIFSTOPPED, *note
     WIFCONTINUED: XREFWIFCONTINUED.

 -- Built-in Function: WTERMSIG (STATUS)
     Given STATUS from a call to 'waitpid', return the number of the
     signal that caused the child process to terminate.  This function
     should only be employed if 'WIFSIGNALED' returned true.

     See also: *note waitpid: XREFwaitpid, *note WIFEXITED:
     XREFWIFEXITED, *note WEXITSTATUS: XREFWEXITSTATUS, *note
     WIFSIGNALED: XREFWIFSIGNALED, *note WCOREDUMP: XREFWCOREDUMP, *note
     WIFSTOPPED: XREFWIFSTOPPED, *note WSTOPSIG: XREFWSTOPSIG, *note
     WIFCONTINUED: XREFWIFCONTINUED.

 -- Built-in Function: WUNTRACED ()
     Return the numerical value of the option argument that may be
     passed to 'waitpid' to indicate that it should also return if the
     child process has stopped but is not traced via the 'ptrace' system
     call

     See also: *note waitpid: XREFwaitpid, *note WNOHANG: XREFWNOHANG,
     *note WCONTINUE: XREFWCONTINUE.

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

     'F_DUPFD'
          Return a duplicate file descriptor.

     'F_GETFD'
          Return the file descriptor flags for FID.

     'F_SETFD'
          Set the file descriptor flags for FID.

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

          'O_RDONLY'
               Open for reading only.

          'O_WRONLY'
               Open for writing only.

          'O_RDWR'
               Open for reading and writing.

          'O_APPEND'
               Append on each write.

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

          'O_NONBLOCK'
               Non-blocking mode.

          'O_SYNC'
               Wait for writes to complete.

          'O_ASYNC'
               Asynchronous I/O.

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

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

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

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

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

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

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

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

     Return 0 if successful, otherwise return -1.

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


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

36.6 Process, Group, and User IDs
=================================

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

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

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

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

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

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

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


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

36.7 Environment Variables
==========================

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

          getenv ("PATH")

     returns a string containing the value of your path.

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


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

36.8 Current Working Directory
==============================

 -- Command: cd DIR
 -- Command: cd
 -- Built-in Function: OLD_DIR = cd DIR
 -- Command: chdir ...
     Change the current working directory to DIR.

     If DIR is omitted, the current directory is changed to the user's
     home directory ("~").

     For example,

          cd ~/octave

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

     'chdir' is an alias for 'cd' and can be used in all of the same
     calling formats.

     Compatibility Note: When called with no arguments, MATLAB prints
     the present working directory rather than changing to the user's
     home directory.

     See also: *note pwd: XREFpwd, *note mkdir: XREFmkdir, *note rmdir:
     XREFrmdir, *note dir: XREFdir, *note ls: XREFls.

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

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

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

     Filenames are subject to shell expansion if they contain any
     wildcard characters '*', '?', '[]'.  If you want to find a literal
     example of a wildcard character you must escape it using the
     backslash operator '\'.

     See also: *note dir: XREFdir, *note readdir: XREFreaddir, *note
     glob: XREFglob, *note what: XREFwhat, *note stat: XREFstat, *note
     filesep: XREFfilesep, *note ls_command: XREFls_command.

 -- Function File: VAL = ls_command ()
 -- Function File: OLD_VAL = ls_command (NEW_VAL)
     Query or set the shell command used by Octave's 'ls' command.

     See also: *note ls: XREFls.

 -- Function File: dir
 -- Function File: dir (DIRECTORY)
 -- Function File: [LIST] = dir (DIRECTORY)
     Display file listing for directory DIRECTORY.

     If DIRECTORY is not specified then list the present working
     directory.

     If a return value is requested, return a structure array with the
     fields

     name
          File or directory name.

     date
          Timestamp of file modification (string value).

     bytes
          File size in bytes.

     isdir
          True if name is a directory.

     datenum
          Timestamp of file modification as serial date number (double).

     statinfo
          Information structure returned from 'stat'.

     If DIRECTORY is a filename, rather than a directory, then return
     information about the named file.  DIRECTORY may also be a list
     rather than a single directory or file.

     DIRECTORY is subject to shell expansion if it contains any wildcard
     characters '*', '?', '[]'.  If you want to find a literal example
     of a wildcard character you must escape it using the backslash
     operator '\'.

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

     See also: *note ls: XREFls, *note readdir: XREFreaddir, *note glob:
     XREFglob, *note what: XREFwhat, *note stat: XREFstat.

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

     See also: *note cd: XREFcd, *note dir: XREFdir, *note ls: XREFls,
     *note mkdir: XREFmkdir, *note rmdir: XREFrmdir.


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

36.9 Password Database Functions
================================

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

'name'
     The user name.

'passwd'
     The encrypted password, if available.

'uid'
     The numeric user id.

'gid'
     The numeric group id.

'gecos'
     The GECOS field.

'dir'
     The home directory.

'shell'
     The initial shell.

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

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

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

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

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

 -- Built-in Function: endpwent ()
     Close the password database.


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

36.10 Group Database Functions
==============================

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

'name'
     The user name.

'passwd'
     The encrypted password, if available.

'gid'
     The numeric group id.

'mem'
     The members of the group.

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

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

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

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

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

 -- Built-in Function: endgrent ()
     Close the group database.


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

36.11 System Information
========================

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

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

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

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

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

     If the argument "arch" is specified, return a string indicating the
     architecture of the computer on which Octave is running.

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

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

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

 -- Built-in Function: nproc ()
 -- Built-in Function: nproc (QUERY)
     Return the current number of available processors.

     If called with the optional argument QUERY, modify how processors
     are counted as follows:

     'all'
          total number of processors.

     'current'
          processors available to the current process.

     'overridable'
          likewise, but overridable through the 'OMP_NUM_THREADS'
          environment variable.

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

     See also: *note isunix: XREFisunix, *note ismac: XREFismac.

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

     See also: *note ismac: XREFismac, *note ispc: XREFispc.

 -- Function File: ismac ()
     Return true if Octave is running on a Mac OS X system and false
     otherwise.

     See also: *note isunix: XREFisunix, *note ispc: XREFispc.

 -- Built-in Function: isieee ()
     Return true if your computer _claims_ to conform to the IEEE
     standard for floating point calculations.  No actual tests are
     performed.

 -- Function File: isdeployed ()
     Return true if the current program has been compiled and is running
     separately from the Octave interpreter and false if it is running
     in the Octave interpreter.  Currently, this function always returns
     false in Octave.

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

     See also: *note EXEC_PATH: XREFEXEC_PATH, *note IMAGE_PATH:
     XREFIMAGE_PATH.

 -- Function File: matlabroot ()
     Return the name of the top-level Octave installation directory.

     This is an alias for the function 'OCTAVE_HOME' provided for
     compatibility.

     See also: *note OCTAVE_HOME: XREFOCTAVE_HOME.

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

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

     This is an alias for the function 'OCTAVE_VERSION' provided for
     compatibility.

     See also: *note OCTAVE_VERSION: XREFOCTAVE_VERSION.

 -- Function File: ver ()
 -- Function File: v = ver ()
 -- Function File: v = ver ("Octave")
 -- Function File: v = ver (PACKAGE)

     Display a header containing the current Octave version number,
     license string, and operating system followed by a list of
     installed packages, versions, and installation directories.

     'v = ver ()'

     Return a vector of structures describing Octave and each installed
     package.  The structure includes the following fields.

     'Name'
          Package name.

     'Version'
          Version of the package.

     'Revision'
          Revision of the package.

     'Date'
          Date of the version/revision.

     'v = ver ("Octave")'

     Return version information for Octave only.

     'v = ver (PACKAGE)'

     Return version information for PACKAGE.

     See also: *note version: XREFversion, *note octave_config_info:
     XREFoctave_config_info.

 -- Function File: compare_versions (V1, V2, OPERATOR)
     Compare two version strings using the given OPERATOR.

     This function assumes that versions V1 and V2 are arbitrarily long
     strings made of numeric and period characters possibly followed by
     an arbitrary string (e.g., "1.2.3", "0.3", "0.1.2+", or
     "1.2.3.4-test1").

     The version is first split into numeric and character portions and
     then the parts are padded to be the same length (i.e., "1.1" would
     be padded to be "1.1.0" when being compared with "1.1.1", and
     separately, the character parts of the strings are padded with
     nulls).

     The operator can be any logical operator from the set

        * "==" equal

        * "<" less than

        * "<=" less than or equal to

        * ">" greater than

        * ">=" greater than or equal to

        * "!=" not equal

        * "~=" not equal

     Note that version "1.1-test2" will compare as greater than
     "1.1-test10".  Also, since the numeric part is compared first, "a"
     compares less than "1a" because the second string starts with a
     numeric part even though 'double ("a")' is greater than 'double
     ("1").'

 -- Command: license
 -- Function File: license ("inuse")
 -- Function File: RETVAL = license ("inuse")
 -- Function File: RETVAL = license ("test", FEATURE)
 -- Function File: license ("test", FEATURE, TOGGLE)
 -- Function File: RETVAL = license ("checkout", FEATURE)

     Display the license of Octave.

     'license ("inuse")'

     Display a list of packages currently being used.

     'RETVAL = license ("inuse")'

     Return a structure containing the fields 'feature' and 'user'.

     'RETVAL = license ("test", FEATURE)'

     Return 1 if a license exists for the product identified by the
     string FEATURE and 0 otherwise.  The argument FEATURE is case
     insensitive and only the first 27 characters are checked.

     'license ("test", FEATURE, TOGGLE)'

     Enable or disable license testing for FEATURE, depending on TOGGLE,
     which may be one of:

     "enable"
          Future tests for the specified license of FEATURE are
          conducted as usual.

     "disable"
          Future tests for the specified license of FEATURE return 0.

     'RETVAL = license ("checkout", FEATURE)'

     Check out a license for FEATURE, returning 1 on success and 0 on
     failure.

     This function is provided for compatibility with MATLAB.

     See also: *note ver: XREFver, *note version: XREFversion.

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

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

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

     'idrss'
          Unshared data size.

     'inblock'
          Number of block input operations.

     'isrss'
          Unshared stack size.

     'ixrss'
          Shared memory size.

     'majflt'
          Number of major page faults.

     'maxrss'
          Maximum data size.

     'minflt'
          Number of minor page faults.

     'msgrcv'
          Number of messages received.

     'msgsnd'
          Number of messages sent.

     'nivcsw'
          Number of involuntary context switches.

     'nsignals'
          Number of signals received.

     'nswap'
          Number of swaps.

     'nvcsw'
          Number of voluntary context switches.

     'oublock'
          Number of block output operations.

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

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


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

36.12 Hashing Functions
=======================

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

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

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

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

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


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

37 Java Interface
*****************

The Java Interface is designed for calling Java functions from within
Octave.  If you want to do the reverse, and call Octave from within
Java, try a library like 'javaOctave'
(<http://kenai.com/projects/javaOctave>) or 'joPas'
(<http://jopas.sourceforge.net>).

* Menu:

* Java Interface Functions::
* Dialog Box Functions::
* FAQ - Frequently asked Questions::


File: octave.info,  Node: Java Interface Functions,  Next: Dialog Box Functions,  Up: Java Interface

37.1 Java Interface Functions
=============================

The following functions are the core of the Java Interface.  They
provide a way to create a Java object, get and set its data fields, and
call Java methods which return results to Octave.

 -- Built-in Function: JOBJ = javaObject (CLASSNAME)
 -- Built-in Function: JOBJ = javaObject (CLASSNAME, ARG1, ...)
     Create a Java object of class CLASSSNAME, by calling the class
     constructor with the arguments ARG1, ...

     The first example below creates an uninitialized object, while the
     second example supplies an initial argument to the constructor.

          x = javaObject ("java.lang.StringBuffer")
          x = javaObject ("java.lang.StringBuffer", "Initial string")

     See also: *note javaMethod: XREFjavaMethod, *note javaArray:
     XREFjavaArray.

   *FIXME:* Need documentation on how fieldnames() is overloaded to
return the methods of a Java object.

   *FIXME:* Need documentation on how to use structure-like indexing to
get fields from Java object.

   *FIXME:* Need documentation on how to use structure-like indexing to
set fields from Java object.

 -- Built-in Function: isjava (X)
     Return true if X is a Java object.

     See also: *note class: XREFclass, *note typeinfo: XREFtypeinfo,
     *note isa: XREFisa, *note javaObject: XREFjavaObject.

 -- Function File: JARY = javaArray (CLASSNAME, SZ)
 -- Function File: JARY = javaArray (CLASSNAME, M, N, ...)

     Create a Java array of size SZ with elements of class CLASSNAME.
     CLASSNAME may be a Java object representing a class or a string
     containing the fully qualified class name.  The size of the object
     may also be specified with individual integer arguments M, N, etc.

     The generated array is uninitialized.  All elements are set to null
     if CLASSNAME is a reference type, or to a default value (usually 0)
     if CLASSNAME is a primitive type.

     Sample code:

          jary = javaArray ("java.lang.String", 2, 2);
          jary(1,1) = "Hello";

     See also: *note javaObject: XREFjavaObject.

 -- Built-in Function: RET = javaMethod (METHODNAME, OBJ)
 -- Built-in Function: RET = javaMethod (METHODNAME, OBJ, ARG1, ...)
     Invoke the method METHODNAME on the Java object OBJ with the
     arguments ARG1, ... For static methods, OBJ can be a string
     representing the fully qualified name of the corresponding class.
     The function returns the result of the method invocation.

     When OBJ is a regular Java object, structure-like indexing can be
     used as a shortcut syntax.  For instance, the two following
     statements are equivalent

            ret = javaMethod ("method1", x, 1.0, "a string")
            ret = x.method1 (1.0, "a string")

     See also: *note methods: XREFmethods, *note javaObject:
     XREFjavaObject.

   *FIXME:* Need documentation on how methods() is overloaded to return
the methods of a Java object.

   The following three functions are used to display and modify the
class path used by the Java Virtual Machine.  This is entirely separate
from Octave's PATH variable and is used by the JVM to find the correct
code to execute.

 -- Function File: javaclasspath ()
 -- Function File: DPATH = javaclasspath ()
 -- Function File: [DPATH, SPATH] = javaclasspath ()
 -- Function File: CLSPATH = javaclasspath (WHAT)
     Return the class path of the Java virtual machine in the form of a
     cell array of strings.

     If called with no inputs:

        * If no output is requested, the dynamic and static classpaths
          are printed to the standard output.

        * If one output value DPATH is requested, the result is the
          dynamic classpath.

        * If two output valuesDPATH and SPATH are requested, the first
          variable will contain the dynamic classpath and the second
          will be contain the static classpath.

     If called with a single input parameter WHAT:

     "-dynamic"
          Return the dynamic classpath.

     "-static"
          Return the static classpath.

     "-all"
          Return both the static and dynamic classpath in a single
          cellstr.

     See also: *note javaaddpath: XREFjavaaddpath, *note javarmpath:
     XREFjavarmpath.

 -- Function File: javaaddpath (CLSPATH)
 -- Function File: javaaddpath (CLSPATH1, ...)
     Add CLSPATH to the dynamic class path of the Java virtual machine.
     CLSPATH may either be a directory where '.class' files are found,
     or a '.jar' file containing Java classes.  Multiple paths may be
     added at once by specifying additional arguments.

     See also: *note javarmpath: XREFjavarmpath, *note javaclasspath:
     XREFjavaclasspath.

 -- Function File: javarmpath (CLSPATH)
 -- Function File: javarmpath (CLSPATH1, ...)
     Remove CLSPATH from the dynamic class path of the Java virtual
     machine.  CLSPATH may either be a directory where '.class' files
     are found, or a '.jar' file containing Java classes.  Multiple
     paths may be removed at once by specifying additional arguments.

     See also: *note javaaddpath: XREFjavaaddpath, *note javaclasspath:
     XREFjavaclasspath.

   The following four functions provide information and control over the
interface between Octave and the Java Virtual Machine.

 -- Function File: usejava (FEATURE)
     Return true if the Java element FEATURE is available.

     Possible features are:

     "awt"
          Abstract Window Toolkit for GUIs.

     "desktop"
          Interactive desktop is running.

     "jvm"
          Java Virtual Machine.

     "swing"
          Swing components for lightweight GUIs.

     'usejava' determines if specific Java features are available in an
     Octave session.  This function is provided for scripts which may
     alter their behavior based on the availability of Java.  The
     feature "desktop" always returns 'false' as Octave has no
     Java-based desktop.  Other features may be available if Octave was
     compiled with the Java Interface and Java is installed.

 -- Function File: javamem ()
 -- Function File: JMEM = javamem ()
     Show the current memory usage of the Java virtual machine (JVM) and
     run the garbage collector.

     When no return argument is given the info is printed to the screen.
     Otherwise, the output cell array JMEM contains Maximum, Total, and
     Free memory (in bytes).

     All Java-based routines are run in the JVM's shared memory pool, a
     dedicated and separate part of memory claimed by the JVM from your
     computer's total memory (which comprises physical RAM and virtual
     memory / swap space on hard disk).

     The maximum allowable memory usage can be configured using the file
     'java.opts'.  The directory where this file resides is determined
     by the environment variable 'OCTAVE_JAVA_DIR'.  If unset, the
     directory where 'javaaddpath.m' resides is used instead (typically
     'OCTAVE_HOME/share/octave/OCTAVE_VERSION/m/java/'

     'java.opts' is a plain text file with one option per line.  The
     default initial memory size and default maximum memory size (which
     are both system dependent) can be overridden like so:

     -Xms64m

     -Xmx512m

     (in megabytes in this example).  You can adapt these values to your
     own requirements if your system has limited available physical
     memory or if you get Java memory errors.

     "Total memory" is what the operating system has currently assigned
     to the JVM and depends on actual and active memory usage.  "Free
     memory" is self-explanatory.  During operation of Java-based Octave
     functions the amount of Total and Free memory will vary, due to
     Java's own cleaning up and your operating system's memory
     management.

 -- Built-in Function: VAL = java_matrix_autoconversion ()
 -- Built-in Function: OLD_VAL = java_matrix_autoconversion (NEW_VAL)
 -- Built-in Function: java_matrix_autoconversion (NEW_VAL, "local")
     Query or set the internal variable that controls whether Java
     arrays are automatically converted to Octave matrices.  The default
     value is false.

     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.

     See also: *note java_unsigned_autoconversion:
     XREFjava_unsigned_autoconversion, *note debug_java: XREFdebug_java.

 -- Built-in Function: VAL = java_unsigned_autoconversion ()
 -- Built-in Function: OLD_VAL = java_unsigned_autoconversion (NEW_VAL)
 -- Built-in Function: java_unsigned_autoconversion (NEW_VAL, "local")
     Query or set the internal variable that controls how integer
     classes are converted when 'java_matrix_autoconversion' is enabled.
     When enabled, Java arrays of class Byte or Integer are converted to
     matrices of class uint8 or uint32 respectively.  The default value
     is true.

     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.

     See also: *note java_matrix_autoconversion:
     XREFjava_matrix_autoconversion, *note debug_java: XREFdebug_java.

 -- Built-in Function: VAL = debug_java ()
 -- Built-in Function: OLD_VAL = debug_java (NEW_VAL)
 -- Built-in Function: debug_java (NEW_VAL, "local")
     Query or set the internal variable that determines whether extra
     debugging information regarding the initialization of the JVM and
     any Java exceptions is printed.

     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.

     See also: *note java_matrix_autoconversion:
     XREFjava_matrix_autoconversion, *note java_unsigned_autoconversion:
     XREFjava_unsigned_autoconversion.


File: octave.info,  Node: Dialog Box Functions,  Next: FAQ - Frequently asked Questions,  Prev: Java Interface Functions,  Up: Java Interface

37.2 Dialog Box Functions
=========================

The following functions all use the Java Interface to provide some form
of dialog box.

 -- Function File: H = msgbox (MSG)
 -- Function File: H = msgbox (MSG, TITLE)
 -- Function File: H = msgbox (MSG, TITLE, ICON)
     Display MSG using a message dialog box.

     The message may have multiple lines separated by newline characters
     ("\n"), or it may be a cellstr array with one element for each
     line.  The optional input TITLE (character string) can be used to
     decorate the dialog caption.

     The optional argument ICON selects a dialog icon.  It can be one of
     "none" (default), "error", "help", or "warn".

     The return value is always 1.

     See also: *note errordlg: XREFerrordlg, *note helpdlg: XREFhelpdlg,
     *note inputdlg: XREFinputdlg, *note listdlg: XREFlistdlg, *note
     questdlg: XREFquestdlg, *note warndlg: XREFwarndlg.

 -- Function File: H = errordlg (MSG)
 -- Function File: H = errordlg (MSG, TITLE)
     Display MSG using an error dialog box.

     The message may have multiple lines separated by newline characters
     ("\n"), or it may be a cellstr array with one element for each
     line.  The optional input TITLE (character string) can be used to
     set the dialog caption.  The default title is "Error Dialog".

     The return value is always 1.

     See also: *note helpdlg: XREFhelpdlg, *note inputdlg: XREFinputdlg,
     *note listdlg: XREFlistdlg, *note msgbox: XREFmsgbox, *note
     questdlg: XREFquestdlg, *note warndlg: XREFwarndlg.

 -- Function File: H = helpdlg (MSG)
 -- Function File: H = helpdlg (MSG, TITLE)
     Display MSG in a help dialog box.

     The message may have multiple lines separated by newline characters
     ("\n"), or it may be a cellstr array with one element for each
     line.  The optional input TITLE (character string) can be used to
     set the dialog caption.  The default title is "Help Dialog".

     The return value is always 1.

     See also: *note errordlg: XREFerrordlg, *note inputdlg:
     XREFinputdlg, *note listdlg: XREFlistdlg, *note msgbox: XREFmsgbox,
     *note questdlg: XREFquestdlg, *note warndlg: XREFwarndlg.

 -- Function File: CSTR = inputdlg (PROMPT)
 -- Function File: CSTR = inputdlg (PROMPT, TITLE)
 -- Function File: CSTR = inputdlg (PROMPT, TITLE, ROWSCOLS)
 -- Function File: CSTR = inputdlg (PROMPT, TITLE, ROWSCOLS, DEFAULTS)
     Return user input from a multi-textfield dialog box in a cell array
     of strings, or an empty cell array if the dialog is closed by the
     Cancel button.

     Inputs:

     PROMPT
          A cell array with strings labeling each text field.  This
          input is required.

     TITLE
          String to use for the caption of the dialog.  The default is
          "Input Dialog".

     ROWSCOLS
          Specifies the size of the text fields and can take three
          forms:

            1. a scalar value which defines the number of rows used for
               each text field.

            2. a vector which defines the individual number of rows used
               for each text field.

            3. a matrix which defines the individual number of rows and
               columns used for each text field.  In the matrix each row
               describes a single text field.  The first column
               specifies the number of input rows to use and the second
               column specifies the text field width.

     DEFAULTS
          A list of default values to place in each text fields.  It
          must be a cell array of strings with the same size as PROMPT.

     See also: *note errordlg: XREFerrordlg, *note helpdlg: XREFhelpdlg,
     *note listdlg: XREFlistdlg, *note msgbox: XREFmsgbox, *note
     questdlg: XREFquestdlg, *note warndlg: XREFwarndlg.

 -- Function File: [SEL, OK] = listdlg (KEY, VALUE, ...)
     Return user inputs from a list dialog box in a vector of selection
     indices SEL and a flag OK indicating how the user closed the dialog
     box.  The value of OK is 1 if the user closed the box with the OK
     button, otherwise it is 0 and SEL is empty.

     The indices in SEL are 1-based.

     The arguments are specified in form of KEY, VALUE pairs.  The
     "ListString" argument pair must be specified.

     Valid KEY and VALUE pairs are:

     "ListString"
          a cell array of strings comprising the content of the list.

     "SelectionMode"
          can be either "Single" or "Multiple" (default).

     "ListSize"
          a vector with two elements WIDTH and HEIGHT defining the size
          of the list field in pixels.  Default is [160 300].

     "InitialValue"
          a vector containing 1-based indices of preselected elements.
          Default is 1 (first item).

     "Name"
          a string to be used as the dialog caption.  Default is "".

     "PromptString"
          a cell array of strings to be displayed above the list field.
          Default is {}.

     "OKString"
          a string used to label the OK button.  Default is "OK".

     "CancelString"
          a string used to label the Cancel button.  Default is
          "Cancel".

     Example:

          [sel, ok] = listdlg ("ListString", {"An item", "another", "yet another"},
                               "SelectionMode", "Multiple");
          if (ok == 1)
            for i = 1:numel (sel)
              disp (sel(i));
            endfor
          endif

     See also: *note errordlg: XREFerrordlg, *note helpdlg: XREFhelpdlg,
     *note inputdlg: XREFinputdlg, *note msgbox: XREFmsgbox, *note
     questdlg: XREFquestdlg, *note warndlg: XREFwarndlg.

 -- Function File: BTN = questdlg (MSG)
 -- Function File: BTN = questdlg (MSG, TITLE)
 -- Function File: BTN = questdlg (MSG, TITLE, DEFAULT)
 -- Function File: BTN = questdlg (MSG, TITLE, BTN1, BTN2, DEFAULT)
 -- Function File: BTN = questdlg (MSG, TITLE, BTN1, BTN2, BTN3,
          DEFAULT)
     Display MSG using a question dialog box and return the caption of
     the activated button.

     The dialog may contain two or three buttons which will all close
     the dialog.

     The message may have multiple lines separated by newline characters
     ("\n"), or it may be a cellstr array with one element for each
     line.  The optional TITLE (character string) can be used to
     decorate the dialog caption.

     The string DEFAULT identifies the default button, which is
     activated by pressing the <ENTER> key.  It must match one of the
     strings given in BTN1, BTN2, or BTN3.

     If only MSG and TITLE are specified, three buttons with the default
     captions "Yes", "No", and "Cancel" are used.

     If only two button captions, BTN1 and BTN2, are specified the
     dialog will have only these two buttons.

     See also: *note errordlg: XREFerrordlg, *note helpdlg: XREFhelpdlg,
     *note inputdlg: XREFinputdlg, *note listdlg: XREFlistdlg, *note
     warndlg: XREFwarndlg.

 -- Function File: H = warndlg (MSG)
 -- Function File: H = warndlg (MSG, TITLE)
     Display MSG using a warning dialog box.

     The message may have multiple lines separated by newline characters
     ("\n"), or it may be a cellstr array with one element for each
     line.  The optional input TITLE (character string) can be used to
     set the dialog caption.  The default title is "Warning Dialog".

     See also: *note helpdlg: XREFhelpdlg, *note inputdlg: XREFinputdlg,
     *note listdlg: XREFlistdlg, *note questdlg: XREFquestdlg.


File: octave.info,  Node: FAQ - Frequently asked Questions,  Prev: Dialog Box Functions,  Up: Java Interface

37.3 FAQ - Frequently asked Questions
=====================================

* Menu:

* How to distinguish between Octave and Matlab?::
* How to make Java classes available?::
* How to create an instance of a Java class?::
* How can I handle memory limitations?::
* Which TeX symbols are implemented in dialog functions?::


File: octave.info,  Node: How to distinguish between Octave and Matlab?,  Next: How to make Java classes available?,  Up: FAQ - Frequently asked Questions

37.3.1 How to distinguish between Octave and Matlab?
----------------------------------------------------

Octave and MATLAB are very similar, but handle Java slightly different.
Therefore it may be necessary to detect the environment and use the
appropriate functions.  The following function can be used to detect the
environment.  Due to the persistent variable it can be called repeatedly
without a heavy performance hit.

   Example:

     %%
     %% Return: true if the environment is Octave.
     %%
     function retval = isOctave
       persistent cacheval;  % speeds up repeated calls

       if isempty (cacheval)
         cacheval = (exist ("OCTAVE_VERSION", "builtin") > 0);
       end

       retval = cacheval;
     end


File: octave.info,  Node: How to make Java classes available?,  Next: How to create an instance of a Java class?,  Prev: How to distinguish between Octave and Matlab?,  Up: FAQ - Frequently asked Questions

37.3.2 How to make Java classes available to Octave?
----------------------------------------------------

Java finds classes by searching a CLASSPATH.  This is a list of Java
archive files and/or directories containing class files.  In Octave the
CLASSPATH is composed of two parts:

   * the STATIC CLASSPATH is initialized once at startup of the JVM, and

   * the DYNAMIC CLASSPATH which can be modified at runtime.

   Octave searches the STATIC CLASSPATH first, then the DYNAMIC
CLASSPATH.  Classes appearing in the STATIC as well as in the DYNAMIC
CLASSPATH will therefore be found in the STATIC CLASSPATH and loaded
from this location.  Classes which will be used frequently or must be
available to all users should be added to the STATIC CLASSPATH.  The
STATIC CLASSPATH is populated once from the contents of a plain text
file named 'javaclasspath.txt' (or 'classpath.txt' historically) when
the Java Virtual Machine starts.  This file contains one line for each
individual classpath to be added to the STATIC CLASSPATH.  These lines
can identify single class files, directories containing class files, or
Java archives with complete class file hierarchies.  Comment lines
starting with a '#' or a '%' character are ignored.

   The search rules for the file 'javaclasspath.txt' (or
'classpath.txt') are:

   * First, Octave tries to locate it in the current directory (where
     Octave was started from).  If such a file is found, it is read and
     defines the initial STATIC CLASSPATH.  Thus, it is possible to
     define a static classpath on a 'per Octave invocation' basis.

   * Next, Octave searches in the user's home directory.  If a file
     'javaclasspath.txt' exists here, its contents are appended to the
     static classpath (if any).  Thus, it is possible to build an
     initial static classpath on a 'per user' basis.

   * Finally, Octave looks for a next occurrence of file
     'javaclasspath.txt' in the m-files directory where Octave Java
     functions live.  This is where 'javaclasspath.m' resides, usually
     something like 'OCTAVE_HOME/share/octave/OCTAVE_VERSION/m/java/'.
     You can find this directory by executing the command

          which javaclasspath

     If this file exists here, its contents are also appended to the
     static classpath.  Note that the archives and class directories
     defined in this last step will affect all users.

   Classes which are used only by a specific script should be placed in
the DYNAMIC CLASSPATH.  This portion of the classpath can be modified at
runtime using the 'javaaddpath' and 'javarmpath' functions.

   Example:

     octave> base_path = "C:/Octave/java_files";

     octave> % add two JARchives to the dynamic classpath
     octave> javaaddpath ([base_path, "/someclasses.jar"]);
     octave> javaaddpath ([base_path, "/moreclasses.jar"]);

     octave> % check the dynamic classpath
     octave> p = javaclasspath;
     octave> disp (p{1});
     C:/Octave/java_files/someclasses.jar
     octave> disp (p{2});
     C:/Octave/java_files/moreclasses.jar

     octave> % remove the first element from the classpath
     octave> javarmpath ([base_path, "/someclasses.jar"]);
     octave> p = javaclasspath;
     octave> disp (p{1});
     C:/Octave/java_files/moreclasses.jar

     octave> % provoke an error
     octave> disp (p{2});
     error: A(I): Index exceeds matrix dimension.

   Another way to add files to the DYNAMIC CLASSPATH exclusively for
your user account is to use the file '.octaverc' which is stored in your
home directory.  All Octave commands in this file are executed each time
you start a new instance of Octave.  The following example adds the
directory 'octave' to Octave's search path and the archive
'myclasses.jar' in this directory to the Java search path.

     % contents of .octaverc:
     addpath ("~/octave");
     javaaddpath ("~/octave/myclasses.jar");


File: octave.info,  Node: How to create an instance of a Java class?,  Next: How can I handle memory limitations?,  Prev: How to make Java classes available?,  Up: FAQ - Frequently asked Questions

37.3.3 How to create an instance of a Java class?
-------------------------------------------------

The function 'javaObject' can be used to create Java objects..

   Example:

     Passenger = javaObject ("package.FirstClass", row, seat);


File: octave.info,  Node: How can I handle memory limitations?,  Next: Which TeX symbols are implemented in dialog functions?,  Prev: How to create an instance of a Java class?,  Up: FAQ - Frequently asked Questions

37.3.4 How can I handle memory limitations?
-------------------------------------------

In order to execute Java code Octave creates a Java Virtual Machine
(JVM). Such a JVM allocates a fixed amount of initial memory and may
expand this pool up to a fixed maximum memory limit.  The default values
depend on the Java version (*note javamem: XREFjavamem.).  The memory
pool is shared by all Java objects running in the JVM.  This strict
memory limit is intended mainly to avoid that runaway applications
inside web browsers or in enterprise servers can consume all memory and
crash the system.  When the maximum memory limit is hit, Java code will
throw exceptions so that applications will fail or behave unexpectedly.

   You can specify options for the creation of the JVM inside a file
named 'java.opts'.  This is a text file where you can enter lines
containing '-X' and '-D' options handed to the JVM during
initialization.

   The directory where the Java options file is located is specified by
the environment variable 'OCTAVE_JAVA_DIR'.  If unset the directory
where 'javaclasspath.m' resides is used instead (typically
'OCTAVE_HOME/share/octave/OCTAVE_VERSION/m/java/').  You can find this
directory by executing

     which javaclasspath

   The '-X' options allow you to increase the maximum amount of memory
available to the JVM.  The following example allows up to 256 Megabytes
to be used by adding the following line to the 'java.opts' file:

     -Xmx256m

   The maximum possible amount of memory depends on your system.  On a
Windows system with 2 Gigabytes main memory you should be able to set
this maximum to about 1 Gigabyte.

   If your application requires a large amount of memory from the
beginning, you can also specify the initial amount of memory allocated
to the JVM.  Adding the following line to the 'java.opts' file starts
the JVM with 64 Megabytes of initial memory:

     -Xms64m

   For more details on the available '-X' options of your Java Virtual
Machine issue the command 'java -X' at the operating system command
prompt and consult the Java documentation.

   The '-D' options can be used to define system properties which can
then be used by Java classes inside Octave.  System properties can be
retrieved by using the 'getProperty()' methods of the 'java.lang.System'
class.  The following example line defines the property MYPROPERTY and
assigns it the string '12.34'.

     -DMyProperty=12.34

   The value of this property can then be retrieved as a string by a
Java object or in Octave:

     octave> javaMethod ("getProperty", "java.lang.System", "MyProperty");
     ans = 12.34

See also: javamem.


File: octave.info,  Node: Which TeX symbols are implemented in dialog functions?,  Prev: How can I handle memory limitations?,  Up: FAQ - Frequently asked Questions

37.3.5 Which TeX symbols are implemented in dialog functions?
-------------------------------------------------------------

The dialog functions contain a translation table for TeX like symbol
codes.  Thus messages and labels can be tailored to show some common
mathematical symbols or Greek characters.  No further TeX formatting
codes are supported.  The characters are translated to their Unicode
equivalent.  However, not all characters may be displayable on your
system.  This depends on the font used by the Java system on your
computer.

   Each TeX symbol code must be terminated by a space character to make
it distinguishable from the surrounding text.  Therefore the string
'\alpha =12.0' will produce the desired result, whereas '\alpha=12.0'
would produce the literal text '\ALPHA=12.0'.

See also: errordlg, helpdlg, inputdlg, listdlg, msgbox, questdlg,
warndlg.


File: octave.info,  Node: Packages,  Next: External Code Interface,  Prev: Java Interface,  Up: Top

38 Packages
***********

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

* Menu:

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


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

38.1 Installing and Removing Packages
=====================================

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

     pkg install image-1.0.0.tar.gz

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

   To see which packages are installed type

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

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

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

     pkg uninstall image

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

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

     pkg install -nodeps my_package_with_dependencies.tar.gz

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

 -- Command: pkg COMMAND PKG_NAME
 -- Command: pkg COMMAND OPTION PKG_NAME
     Manage packages (groups of add-on functions) for Octave.  Different
     actions are available depending on the value of COMMAND.

     Available commands:

     'install'
          Install named packages.  For example,

               pkg install image-1.0.0.tar.gz

          installs the package found in the file 'image-1.0.0.tar.gz'.

          The OPTION variable can contain options that affect the manner
          in which a package is installed.  These options can be one or
          more of

          '-nodeps'
               The package manager will disable dependency checking.
               With this option it is possible to install a package even
               when it depends on another package which is not installed
               on the system.  *Use this option with care.*

          '-noauto'
               The package manager will not automatically load the
               installed package when starting Octave.  This overrides
               any setting within the package.

          '-auto'
               The package manager will automatically load the installed
               package when starting Octave.  This overrides any setting
               within the package.

          '-local'
               A local installation (package available only to current
               user) is forced, even if the user has system privileges.

          '-global'
               A global installation (package available to all users) is
               forced, even if the user doesn't normally have system
               privileges.

          '-forge'
               Install a package directly from the Octave-Forge
               repository.  This requires an internet connection and the
               cURL library.

          '-verbose'
               The package manager will print the output of all commands
               as they are performed.

     'update'
          Check installed Octave-Forge packages against repository and
          update any outdated items.  This requires an internet
          connection and the cURL library.  Usage:

               pkg update

     'uninstall'
          Uninstall named packages.  For example,

               pkg uninstall image

          removes the 'image' package from the system.  If another
          installed package depends on the 'image' package an error will
          be issued.  The package can be uninstalled anyway by using the
          '-nodeps' option.

     'load'
          Add named packages to the path.  After loading a package it is
          possible to use the functions provided by the package.  For
          example,

               pkg load image

          adds the 'image' package to the path.  It is possible to load
          all installed packages at once with the keyword 'all'.  Usage:

               pkg load all

     'unload'
          Remove named packages from the path.  After unloading a
          package it is no longer possible to use the functions provided
          by the package.  It is possible to unload all installed
          packages at once with the keyword 'all'.  Usage:

               pkg unload all

     'list'
          Show the list of currently installed packages.  For example,

               installed_packages = pkg ("list")

          returns a cell array containing a structure for each installed
          package.

          If two output arguments are requested 'pkg' splits the list of
          installed packages into those which were installed by the
          current user, and those which were installed by the system
          administrator.

               [user_packages, system_packages] = pkg ("list")

          The option "-forge" lists packages available at the
          Octave-Forge repository.  This requires an internet connection
          and the cURL library.  For example:

               oct_forge_pkgs = pkg ("list", "-forge")

     'describe'
          Show a short description of the named installed packages, with
          the option "-verbose" also list functions provided by the
          package.  For example,

               pkg describe -verbose all

          will describe all installed packages and the functions they
          provide.  If one output is requested a cell of structure
          containing the description and list of functions of each
          package is returned as output rather than printed on screen:

               desc = pkg ("describe", "secs1d", "image")

          If any of the requested packages is not installed, pkg returns
          an error, unless a second output is requested:

               [desc, flag] = pkg ("describe", "secs1d", "image")

          FLAG will take one of the values "Not installed", "Loaded", or
          "Not loaded" for each of the named packages.

     'prefix'
          Set the installation prefix directory.  For example,

               pkg prefix ~/my_octave_packages

          sets the installation prefix to '~/my_octave_packages'.
          Packages will be installed in this directory.

          It is possible to get the current installation prefix by
          requesting an output argument.  For example:

               pfx = pkg ("prefix")

          The location in which to install the architecture dependent
          files can be independently specified with an addition
          argument.  For example:

               pkg prefix ~/my_octave_packages ~/my_arch_dep_pkgs

     'local_list'
          Set the file in which to look for information on locally
          installed packages.  Locally installed packages are those that
          are available only to the current user.  For example:

               pkg local_list ~/.octave_packages

          It is possible to get the current value of local_list with the
          following

               pkg local_list

     'global_list'
          Set the file in which to look for information on globally
          installed packages.  Globally installed packages are those
          that are available to all users.  For example:

               pkg global_list /usr/share/octave/octave_packages

          It is possible to get the current value of global_list with
          the following

               pkg global_list

     'build'
          Build a binary form of a package or packages.  The binary file
          produced will itself be an Octave package that can be
          installed normally with 'pkg'.  The form of the command to
          build a binary package is

               pkg build builddir image-1.0.0.tar.gz ...

          where 'builddir' is the name of a directory where the
          temporary installation will be produced and the binary
          packages will be found.  The options '-verbose' and '-nodeps'
          are respected, while all other options are ignored.

     'rebuild'
          Rebuild the package database from the installed directories.
          This can be used in cases where the package database has been
          corrupted.  It can also take the '-auto' and '-noauto' options
          to allow the autoloading state of a package to be changed.
          For example,

               pkg rebuild -noauto image

          will remove the autoloading status of the image package.


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

38.2 Using Packages
===================

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

     pkg load package_name

where 'package_name' is the name of the package to be added to the path.

   In much the same way a package can be removed from the Octave path by
typing

     pkg unload package_name


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

38.3 Administrating Packages
============================

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

     pkg prefix new_installation_directory

The current installation directory can be retrieved by typing

     current_installation_directory = pkg prefix

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

     pkg local_list /path/to/new_file

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


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

38.4 Creating Packages
======================

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

'package/CITATION'
     This is am optional file describing instructions on how to cite the
     package for publication.  It will be displayed verbatim by the
     function 'citation'.

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

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

'package/ChangeLog'
     This is an optional file describing all the changes made to the
     package source files.

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

'package/NEWS'
     This is an optional file describing all user-visible changes worth
     mentioning.  As this file increases on size, old entries can be
     moved into 'package/ONEWS'.

'package/ONEWS'
     This is an optional file describing old entries from the 'NEWS'
     file.

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

          ln -s foo.oct bar.oct

     with an autoload directive like

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

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

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

'package/pre_install.m'
     This is an optional function that is run prior to the installation
     of a package.  This function is called with a single argument, a
     struct with fields names after the data in the 'DESCRIPTION', and
     the paths where the package functions will be installed.

'package/post_install.m'
     This is an optional function that is run after the installation of
     a package.  This function is called with a single argument, a
     struct with fields names after the data in the 'DESCRIPTION', and
     the paths where the package functions were installed.

'package/on_uninstall.m'
     This is an optional function that is run prior to the removal of a
     package.  This function is called with a single argument, a struct
     with fields names after the data in the 'DESCRIPTION', the paths
     where the package functions are installed, and whether the package
     is currently loaded.

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

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

'package/src'
     An optional directory containing code that must be built prior to
     the packages installation.  The Octave package manager will execute
     './configure' in this directory if this script exists, and will
     then call 'make' if a file 'Makefile' exists in this directory.
     'make install' will however not be called.  The environment
     variables 'MKOCTFILE', 'OCTAVE_CONFIG', and 'OCTAVE' will be set to
     the full paths of the programs 'mkoctfile', 'octave-config', and
     'octave', respectively, of the correct version when 'configure' and
     'make' are called.  If a file called 'FILES' exists all files
     listed there will be copied to the 'inst' directory, so they also
     will be installed.  If the 'FILES' file doesn't exist, 'src/*.m'
     and 'src/*.oct' will be copied to the 'inst' directory.

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

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

* Menu:

* The DESCRIPTION File::
* The INDEX File::
* PKG_ADD and PKG_DEL Directives::
* Missing Components::


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

38.4.1 The DESCRIPTION File
---------------------------

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

   * Lines starting with '#' are comments.

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

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

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

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

   The package manager currently recognizes the following keywords

'Name'
     Name of the package.

'Version'
     Version of the package.  A package version must be 3 numbers
     separated by a dot.

'Date'
     Date of last update.

'Author'
     Original author of the package.

'Maintainer'
     Maintainer of the package.

'Title'
     A one line description of the package.

'Description'
     A one paragraph description of the package.

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

'Problems'
     Optional list of known problems.

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

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

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

          Depends: package (>= 1.0.0)

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

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

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

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

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

     BuildRequires: libtermcap-devel [Mandriva] libtermcap2-devel

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


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

38.4.2 The INDEX File
---------------------

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

   * Lines beginning with '#' are comments.

   * The first non-comment line should look like this

          toolbox >> Toolbox name

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

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

The format can be summarized with the following example:

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

   If you wish to refer to a function that users might expect to find in
your package but is not there, providing a work around or pointing out
that the function is available elsewhere, you can use:

     fn = workaround description

This workaround description will not appear when listing functions in
the package with 'pkg describe' but they will be published in the HTML
documentation online.  Workaround descriptions can use any HTML markup,
but keep in mind that it will be enclosed in a bold-italic environment.
For the special case of:

     fn = use <code>alternate expression</code>

the bold-italic is automatically suppressed.  You will need to use
'<code>' even in references:

     fn = use <a href="someothersite.html"><code>fn</code></a>

Sometimes functions are only partially compatible, in which case you can
list the non-compatible cases separately.  To refer to another function
in the package, use '<f>fn</f>'.  For example:

     eig (a, b) = use <f>qz</f>

Since sites may have many missing functions, you can define a macro
rather than typing the same link over and again.

     $id = expansion

defines the macro id.  You can use '$id' anywhere in the description and
it will be expanded.  For example:

     $TSA = see <a href="link_to_spctools">SPC Tools</a>
     arcov = $TSA <code>armcv</code>

id is any string of letters, numbers and '_'.


File: octave.info,  Node: PKG_ADD and PKG_DEL Directives,  Next: Missing Components,  Prev: The INDEX File,  Up: Creating Packages

38.4.3 PKG_ADD and PKG_DEL Directives
-------------------------------------

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

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

     ## PKG_ADD: some_octave_command

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

     // PKG_ADD: some_octave_command

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


File: octave.info,  Node: Missing Components,  Prev: PKG_ADD and PKG_DEL Directives,  Up: Creating Packages

38.4.4 Missing Components
-------------------------

If a package relies on a component, such as another Octave package, that
may not be present it may be useful to install a function which informs
users what to do when a particular component is missing.  The function
must be written by the package maintainer and registered with Octave
using 'missing_component_hook'.

 -- Built-in Function: VAL = missing_component_hook ()
 -- Built-in Function: OLD_VAL = missing_component_hook (NEW_VAL)
 -- Built-in Function: missing_component_hook (NEW_VAL, "local")
     Query or set the internal variable that specifies the function to
     call when a component of Octave is missing.  This can be useful for
     packagers that may split the Octave installation into multiple
     sub-packages, for example, to provide a hint to users for how to
     install the missing components.

     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.

     The hook function is expected to be of the form

          FCN (COMPONENT)

     Octave will call FCN with the name of the function that requires
     the component and a string describing the missing component.  The
     hook function should return an error message to be displayed.

     See also: *note missing_function_hook: XREFmissing_function_hook.


File: octave.info,  Node: External Code Interface,  Next: Test and Demo Functions,  Prev: Packages,  Up: Top

Appendix A External Code Interface
**********************************

“The sum of human wisdom is not contained in any one language" --Ezra
Pound

   Octave is a fantastic language for solving many problems in science
and engineering.  However, it is not the only computer language and
there are times when you may want to use code written in other
languages.  Good reasons for doing so include: 1) not re-inventing the
wheel; existing function libraries which have been thoroughly tested and
debugged or large scale simulation codebases are a good example, 2)
accessing unique capabilities of a different language; for example the
well-known regular expression functions of Perl (but don't do that
because 'regexp' already exists in Octave).

   Performance should generally *not* be a reason for using compiled
extensions.  Although compiled extensions can run faster, particularly
if they replace a loop in Octave code, this is almost never the best
path to take.  First, there are many techniques to speed up Octave
performance while remaining within the language.  Second, Octave is a
high-level language that makes it easy to perform common mathematical
tasks.  Giving that up means shifting the focus from solving the real
problem to solving a computer programming problem.  It means returning
to low-level constructs such as pointers, memory management,
mathematical overflow/underflow, etc.  Because of the low level nature,
and the fact that the compiled code is executed outside of Octave, there
is the very real possibility of crashing the interpreter and losing
work.

   Before going further, you should first determine if you really need
to bother writing code outside of Octave.

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

     Even when a function already exists outside the language, it may be
     better to simply reproduce the behavior in an m-file rather than
     attempt to interface to the outside code.

   * Is the code thoroughly optimized for Octave?

     If performance is an issue you should always start with the
     in-language techniques for getting better performance.  Chief among
     these is vectorization (*note Vectorization and Faster Code
     Execution::) which not only makes the code concise and more
     understandable but improves performance (10X-100X). If loops must
     be used, make sure that the allocation of space for variables takes
     place outside the loops using an assignment to a matrix of the
     right size, or zeros.

   * Does the code make as much use as possible of existing built-in
     library routines?

     These routines are highly optimized and many do not carry the
     overhead of being interpreted.

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

     It will take time to learn Octave's interface for external code and
     there will inevitably be issues with tools such as compilers.

   With that said, Octave offers a versatile interface for including
chunks of compiled code as dynamically linked extensions.  These
dynamically linked functions can be called from the interpreter in the
same manner as any ordinary function.  The interface is bi-directional
and external code can call Octave functions (like 'plot') which
otherwise might be very difficult to develop.

   The interface is centered around supporting the languages C++, C, and
Fortran.  Octave itself is written in C++ and can call external C++/C
code through its native oct-file interface.  The C language is also
supported through the mex-file interface for compatibility with MATLAB.
Fortran code is easiest to reach through the oct-file interface.

   Because many other languages provide C or C++ APIs it is relatively
simple to build bridges between Octave and other languages.  This is
also a way to bridge to hardware resources which often have device
drivers written in C.

* Menu:

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


File: octave.info,  Node: Oct-Files,  Next: Mex-Files,  Up: External Code Interface

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

* Menu:

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


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

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

Oct-files are pieces of C++ code that have been compiled with the Octave
API into a dynamically loadable object.  They take their name from the
file which contains the object which has the extension '.oct'.

   Finding a C++ compiler, using the correct switches, adding the right
include paths for header files, etc.  is a difficult task.  Octave
automates this by providing the 'mkoctfile' command with which to build
oct-files.  The command is available from within Octave or at the shell
command line.

 -- Command: mkoctfile [-options] file ...
 -- Function File: [OUTPUT, STATUS = mkoctfile (...)

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

     'mkoctfile' can be called from the shell prompt or from the Octave
     prompt.  Calling it from the Octave prompt simply delegates the
     call to the shell prompt.  The output is stored in the OUTPUT
     variable and the exit status in the STATUS variable.

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

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

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

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

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

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

     '-R DIR'
          Add the run-time path to the link command.

     '-Wl,...'
          Pass flags though the linker like "-Wl,-rpath=...".  The
          quotes are needed since commas are interpreted as command
          separators.

     '-W...'
          Pass flags though the compiler like "-Wa,OPTION".

     '-c'
          Compile but do not link.

     '-g'
          Enable debugging options for compilers.

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

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

                  ALL_CFLAGS                FFTW3F_LIBS
                  ALL_CXXFLAGS              FLIBS
                  ALL_FFLAGS                FPICFLAG
                  ALL_LDFLAGS               INCFLAGS
                  BLAS_LIBS                 LAPACK_LIBS
                  CC                        LDFLAGS
                  CFLAGS                    LD_CXX
                  CPICFLAG                  LD_STATIC_FLAG
                  CPPFLAGS                  LFLAGS
                  CXX                       LIBOCTAVE
                  CXXFLAGS                  LIBOCTINTERP
                  CXXPICFLAG                LIBS
                  DEPEND_EXTRA_SED_PATTERN  OCTAVE_LIBS
                  DEPEND_FLAGS              OCTAVE_LINK_DEPS
                  DL_LD                     OCT_LINK_DEPS
                  DL_LDFLAGS                RDYNAMIC_FLAG
                  EXEEXT                    READLINE_LIBS
                  F77                       SED
                  F77_INTEGER_8_FLAG        XTRA_CFLAGS
                  FFLAGS                    XTRA_CXXFLAGS
                  FFTW3_LDFLAGS
                  FFTW3_LIBS
                  FFTW3F_LDFLAGS


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

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

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

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

     'file'
          The file to compile or link.  Recognized file types are

                  .c    C source
                  .cc   C++ source
                  .C    C++ source
                  .cpp  C++ source
                  .f    Fortran source (fixed form)
                  .F    Fortran source (fixed form)
                  .f90  Fortran source (free form)
                  .F90  Fortran source (free form)
                  .o    object file
                  .a    library file

   Consider the following short example which introduces the basics of
writing a C++ function that can be linked to Octave.

     #include <octave/oct.h>

     DEFUN_DLD (helloworld, args, nargout,
                "Hello World Help String")
     {
       int nargin = args.length ();

       octave_stdout << "Hello World has "
                     << nargin << " input arguments and "
                     << nargout << " output arguments.\n";

       return octave_value_list ();
     }


   The first critical line is '#include <octave/oct.h>' which makes
available most of the definitions necessary for a C++ oct-file.  Note
that 'octave/oct.h' is a C++ header and cannot be directly '#include''ed
in a C source file, nor any other language.

   Included by 'oct.h' is a definition for the macro 'DEFUN_DLD' which
creates a dynamically loaded function.  This macro takes four arguments:

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

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

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

  4. The string to use for the help text of the function.

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

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

     mkoctfile helloworld.cc

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

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

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

   Subsequent sections show how to use specific classes from Octave's
core internals.  Base classes like dMatrix (a matrix of double values)
are found in the directory 'liboctave/array'.  The definitive reference
for how to use a particular class is the header file itself.  However,
it is often enough just to study the examples in the manual in order to
be able to use the class.


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

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

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

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

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

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

   These are the basic two-dimensional matrix types of Octave.  In
addition there are a number of multi-dimensional array types including

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

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

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

'int8NDArray'
'int16NDArray'
'int32NDArray'
'int64NDArray'
     8, 16, 32, and 64-bit signed array classes defined in
     'int8NDArray.h', 'int16NDArray.h', etc.

'uint8NDArray'
'uint16NDArray'
'uint32NDArray'
'uint64NDArray'
     8, 16, 32, and 64-bit unsigned array classes defined in
     'uint8NDArray.h', 'uint16NDArray.h', etc.

   There are several basic ways of constructing matrices or
multi-dimensional arrays.  Using the class 'Matrix' as an example one
can

   * Create an empty matrix or array with the empty constructor.  For
     example:

          Matrix a;

     This can be used for all matrix and array types.

   * Define the dimensions of the matrix or array with a dim_vector
     which has the same characteristics as the vector returned from
     'size'.  For example:

          dim_vector dv (2);
          dv(0) = 2; dv(1) = 3;  // 2 rows, 3 columns
          Matrix a (dv);

     This can be used on all matrix and array types.

   * Define the number of rows and columns in the matrix.  For example:

          Matrix a (2, 2)

     However, this constructor can only be used with matrix types.

   These types all share a number of basic methods and operators.  Many
bear a resemblance to functions that exist in the interpreter.  A
selection of useful methods include

 -- Method: T& operator () (octave_idx_type)
 -- Method: T& elem (octave_idx_type)
     The '()' operator or 'elem' method allow the values of the matrix
     or array to be read or set.  These can take a single argument,
     which is of type 'octave_idx_type', that is the index into the
     matrix or array.  Additionally, the matrix type allows two argument
     versions of the '()' operator and elem method, giving the row and
     column index of the value to obtain or set.

   Note that these functions do significant error checking and so in
some circumstances the user might prefer to access the data of the array
or matrix directly through the fortran_vec method discussed below.

 -- Method: octave_idx_type numel (void) const
     The total number of elements in the matrix or array.

 -- Method: size_t byte_size (void) const
     The number of bytes used to store the matrix or array.

 -- Method: dim_vector dims (void) const
     The dimensions of the matrix or array in value of type dim_vector.

 -- Method: int ndims (void) const
     The number of dimensions of the matrix or array.  Matrices are 2-D,
     but arrays can be N-dimensional.

 -- Method: void resize (const dim_vector&)
     A method taking either an argument of type 'dim_vector', or in the
     case of a matrix two arguments of type 'octave_idx_type' defining
     the number of rows and columns in the matrix.

 -- Method: T* fortran_vec (void)
     This method returns a pointer to the underlying data of the matrix
     or array so that it can be manipulated directly, either within
     Octave or by an external library.

   Operators such an '+', '-', or '*' can be used on the majority of the
matrix and array types.  In addition there are a number of methods that
are of interest only for matrices such as 'transpose', 'hermitian',
'solve', etc.

   The typical way to extract a matrix or array from the input arguments
of 'DEFUN_DLD' function is as follows

     #include <octave/oct.h>

     DEFUN_DLD (addtwomatrices, args, , "Add A to B")
     {
       int nargin = args.length ();

       if (nargin != 2)
         print_usage ();
       else
         {
           NDArray A = args(0).array_value ();
           NDArray B = args(1).array_value ();
           if (! error_state)
             return octave_value (A + B);
         }

       return octave_value_list ();
     }


   To avoid segmentation faults causing Octave to abort this function
explicitly checks that there are sufficient arguments available before
accessing these arguments.  It then obtains two multi-dimensional arrays
of type 'NDArray' and adds these together.  Note that the array_value
method is called without using the 'is_matrix_type' type, and instead
the error_state is checked before returning 'A + B'.  The reason to
prefer this is that the arguments might be a type that is not an
'NDArray', but it would make sense to convert it to one.  The
'array_value' method allows this conversion to be performed
transparently if possible, and sets 'error_state' if it is not.

   'A + B', operating on two 'NDArray''s returns an 'NDArray', which is
cast to an 'octave_value' on the return from the function.  An example
of the use of this demonstration function is

     addtwomatrices (ones (2, 2), eye (2, 2))
           =>  2  1
               1  2

   A list of the basic 'Matrix' and 'Array' types, the methods to
extract these from an 'octave_value', and the associated header file is
listed below.

Type                   Function                      Source Code
----------------------------------------------------------------------------
'RowVector'            'row_vector_value'            'dRowVector.h'
'ComplexRowVector'     'complex_row_vector_value'    'CRowVector.h'
'ColumnVector'         'column_vector_value'         'dColVector.h'
'ComplexColumnVector'  'complex_column_vector_value' 'CColVector.h'
'Matrix'               'matrix_value'                'dMatrix.h'
'ComplexMatrix'        'complex_matrix_value'        'CMatrix.h'
'boolMatrix'           'bool_matrix_value'           'boolMatrix.h'
'charMatrix'           'char_matrix_value'           'chMatrix.h'
'NDArray'              'array_value'                 'dNDArray.h'
'ComplexNDArray'       'complex_array_value'         'CNDArray.h'
'boolNDArray'          'bool_array_value'            'boolNDArray.h'
'charNDArray'          'char_array_value'            'charNDArray.h'
'int8NDArray'          'int8_array_value'            'int8NDArray.h'
'int16NDArray'         'int16_array_value'           'int16NDArray.h'
'int32NDArray'         'int32_array_value'           'int32NDArray.h'
'int64NDArray'         'int64_array_value'           'int64NDArray.h'
'uint8NDArray'         'uint8_array_value'           'uint8NDArray.h'
'uint16NDArray'        'uint16_array_value'          'uint16NDArray.h'
'uint32NDArray'        'uint32_array_value'          'uint32NDArray.h'
'uint64NDArray'        'uint64_array_value'          'uint64NDArray.h'


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

A.1.3 Character Strings in Oct-Files
------------------------------------

A character string in Octave is just a special 'Array' class.  Consider
the example:

     #include <octave/oct.h>

     DEFUN_DLD (stringdemo, args, , "String Demo")
     {
       octave_value_list retval;
       int nargin = args.length ();

       if (nargin != 1)
         print_usage ();
       else
         {
           charMatrix ch = args(0).char_matrix_value ();

           if (! error_state)
             {
               retval(1) = octave_value (ch, '\'');  // Single Quote String

               octave_idx_type nr = ch.rows ();
               for (octave_idx_type i = 0; i < nr / 2; i++)
                 {
                   std::string tmp = ch.row_as_string (i);
                   ch.insert (ch.row_as_string (nr-i-1).c_str (), i, 0);
                   ch.insert (tmp.c_str (), nr-i-1, 0);
                 }
               retval(0) = octave_value (ch, '"');  // Double Quote String
             }
         }
       return retval;
     }


   An example of the use of this function is

     s0 = ["First String"; "Second String"];
     [s1,s2] = stringdemo (s0)
     => s1 = Second String
             First String

     => s2 = First String
             Second String

     typeinfo (s2)
     => sq_string
     typeinfo (s1)
     => string

   One additional complication of strings in Octave is the difference
between single quoted and double quoted strings.  To find out if an
'octave_value' contains a single or double quoted string use one of the
predicate tests shown below.

     if (args(0).is_sq_string ())
       octave_stdout << "First argument is a single quoted string\n";
     else if (args(0).is_dq_string ())
       octave_stdout << "First argument is a double quoted string\n";

   Note, however, that both types of strings are represented by the
'charNDArray' type, and so when assigning to an 'octave_value', the type
of string should be specified.  For example:

     octave_value_list retval;
     charNDArray c;
     ...
     // Create single quoted string
     retval(1) = octave_value (ch);        // default constructor is sq_string
                OR
     retval(1) = octave_value (ch, '\'');  // explicitly create sq_string

     // Create a double quoted string
     retval(0) = octave_value (ch, '"');


File: octave.info,  Node: Cell Arrays in Oct-Files,  Next: Structures in Oct-Files,  Prev: Character Strings in Oct-Files,  Up: Oct-Files

A.1.4 Cell Arrays in Oct-Files
------------------------------

Octave's cell type is also available from within oct-files.  A cell
array is just an array of 'octave_value's, and thus each element of the
cell array can be treated just like any other 'octave_value'.  A simple
example is

     #include <octave/oct.h>
     #include <octave/Cell.h>

     DEFUN_DLD (celldemo, args, , "Cell Demo")
     {
       octave_value_list retval;
       int nargin = args.length ();

       if (nargin != 1)
         print_usage ();
       else
         {
           Cell c = args(0).cell_value ();
           if (! error_state)
             for (octave_idx_type i = 0; i < c.numel (); i++)
               {
                 retval(i) = c(i);          // using operator syntax
                 //retval(i) = c.elem (i);  // using method syntax
               }
         }

       return retval;
     }


   Note that cell arrays are used less often in standard oct-files and
so the 'Cell.h' header file must be explicitly included.  The rest of
the example extracts the 'octave_value's one by one from the cell array
and returns them as individual return arguments.  For example:

     [b1, b2, b3] = celldemo ({1, [1, 2], "test"})
     =>
     b1 =  1
     b2 =

        1   2

     b3 = test


File: octave.info,  Node: Structures in Oct-Files,  Next: Sparse Matrices in Oct-Files,  Prev: Cell Arrays in Oct-Files,  Up: Oct-Files

A.1.5 Structures in Oct-Files
-----------------------------

A structure in Octave is a map between a number of fields represented
and their values.  The Standard Template Library 'map' class is used,
with the pair consisting of a 'std::string' and an Octave 'Cell'
variable.

   A simple example demonstrating the use of structures within oct-files
is

     #include <octave/oct.h>
     #include <octave/ov-struct.h>

     DEFUN_DLD (structdemo, args, , "Struct Demo")
     {
       octave_value retval;
       int nargin = args.length ();

       if (args.length () == 2)
         {
           octave_scalar_map arg0 = args(0).scalar_map_value ();
           //octave_map arg0 = args(0).map_value ();

           if (! error_state)
             {
               std::string arg1 = args(1).string_value ();

               if (! error_state)
                 {
                   octave_value tmp = arg0.contents (arg1);
                   //octave_value tmp = arg0.contents (arg1)(0);

                   if (tmp.is_defined ())
                     {
                       octave_scalar_map st;

                       st.assign ("selected", tmp);

                       retval = octave_value (st);
                     }
                   else
                     error ("structdemo: struct does not have a field named '%s'\n",
                            arg1.c_str ());
                 }
               else
                 error ("structdemo: ARG2 must be a character string");
             }
           else
             error ("structdemo: ARG1 must be a struct");
         }
       else
         print_usage ();

       return retval;
     }


   An example of its use is

     x.a = 1; x.b = "test"; x.c = [1, 2];
     structdemo (x, "b")
     => selected = test

   The example above specifically uses the 'octave_scalar_map' class
which is for representing a single struct.  For structure arrays the
'octave_map' class is used instead.  The commented code shows how the
demo could be modified to handle a structure array.  In that case the
'contents' method returns a 'Cell' which may have more than one element.
Therefore, to obtain the underlying 'octave_value' in this single-struct
example we write

     octave_value tmp = arg0.contents (arg1)(0);

where the trailing (0) is the () operator on the 'Cell' object.  If this
were a true structure array with multiple elements we could iterate over
the elements using the () operator.

   Structures are a relatively complex data container and there are more
functions available in 'oct-map.h' which make coding with them easier
than relying on just 'contents'.


File: octave.info,  Node: Sparse Matrices in Oct-Files,  Next: Accessing Global Variables in Oct-Files,  Prev: Structures in Oct-Files,  Up: Oct-Files

A.1.6 Sparse Matrices in Oct-Files
----------------------------------

There are three classes of sparse objects that are of interest to the
user.

'SparseMatrix'
     A double precision sparse matrix class

'SparseComplexMatrix'
     A complex sparse matrix class

'SparseBoolMatrix'
     A boolean sparse matrix class

   All of these classes inherit from the 'Sparse<T>' template class, and
so all have similar capabilities and usage.  The 'Sparse<T>' class was
based on Octave's 'Array<T>' class, and so users familiar with Octave's
'Array' classes will be comfortable with the use of the sparse classes.

   The sparse classes will not be entirely described in this section,
due to their similarity with the existing 'Array' classes.  However,
there are a few differences due the different nature of sparse objects,
and these will be described.  First, although it is fundamentally
possible to have N-dimensional sparse objects, the Octave sparse classes
do not allow them at this time; All instances of the sparse classes must
be 2-dimensional.  This means that 'SparseMatrix' is actually more
similar to Octave's 'Matrix' class than its 'NDArray' class.

* Menu:

* Array and Sparse Class Differences::
* Creating Sparse Matrices in Oct-Files::
* Using Sparse Matrices in Oct-Files::


File: octave.info,  Node: Array and Sparse Class Differences,  Next: Creating Sparse Matrices in Oct-Files,  Up: Sparse Matrices in Oct-Files

A.1.6.1 Array and Sparse Class Differences
..........................................

The number of elements in a sparse matrix is considered to be the number
of non-zero elements rather than the product of the dimensions.
Therefore

     SparseMatrix sm;
     ...
     int nel = sm.nelem ();

returns the number of non-zero elements.  If the user really requires
the number of elements in the matrix, including the non-zero elements,
they should use 'numel' rather than 'nelem'.  Note that for very large
matrices, where the product of the two dimensions is larger than the
representation of an unsigned int, then 'numel' can overflow.  An
example is 'speye (1e6)' which will create a matrix with a million rows
and columns, but only a million non-zero elements.  Therefore the number
of rows by the number of columns in this case is more than two hundred
times the maximum value that can be represented by an unsigned int.  The
use of 'numel' should therefore be avoided useless it is known it won't
overflow.

   Extreme care must be take with the elem method and the "()" operator,
which perform basically the same function.  The reason is that if a
sparse object is non-const, then Octave will assume that a request for a
zero element in a sparse matrix is in fact a request to create this
element so it can be filled.  Therefore a piece of code like

     SparseMatrix sm;
     ...
     for (int j = 0; j < nc; j++)
       for (int i = 0; i < nr; i++)
         std::cerr << " (" << i << "," << j << "): " << sm(i,j) << std::endl;

is a great way of turning the sparse matrix into a dense one, and a very
slow way at that since it reallocates the sparse object at each zero
element in the matrix.

   An easy way of preventing the above from happening is to create a
temporary constant version of the sparse matrix.  Note that only the
container for the sparse matrix will be copied, while the actual
representation of the data will be shared between the two versions of
the sparse matrix.  So this is not a costly operation.  For example, the
above would become

     SparseMatrix sm;
     ...
     const SparseMatrix tmp (sm);
     for (int j = 0; j < nc; j++)
       for (int i = 0; i < nr; i++)
         std::cerr << " (" << i << "," << j << "): " << tmp(i,j) << std::endl;

   Finally, as the sparse types aren't represented by a contiguous block
of memory, the 'fortran_vec' method of the 'Array<T>' is not available.
It is, however, replaced by three separate methods 'ridx', 'cidx' and
'data', that access the raw compressed column format that Octave sparse
matrices are stored in.  These methods can be used in a manner similar
to 'elem' to allow the matrix to be accessed or filled.  However, in
that case it is up to the user to respect the sparse matrix compressed
column format.


File: octave.info,  Node: Creating Sparse Matrices in Oct-Files,  Next: Using Sparse Matrices in Oct-Files,  Prev: Array and Sparse Class Differences,  Up: Sparse Matrices in Oct-Files

A.1.6.2 Creating Sparse Matrices in Oct-Files
.............................................

There are several useful alternatives for creating a sparse matrix.  The
first is to create three vectors representing the row index, column
index, and data values, and from these create the matrix.  The second
alternative is to create a sparse matrix with the appropriate amount of
space and then fill in the values.  Both techniques have their
advantages and disadvantages.

   Below is an example of creating a small sparse matrix using the first
technique

     int nz = 4, nr = 3, nc = 4;

     ColumnVector ridx (nz);
     ColumnVector cidx (nz);
     ColumnVector data (nz);

     ridx(0) = 0; cidx(0) = 0; data(0) = 1;
     ridx(1) = 0; cidx(1) = 1; data(1) = 2;
     ridx(2) = 1; cidx(2) = 3; data(2) = 3;
     ridx(3) = 2; cidx(3) = 3; data(3) = 4;
     SparseMatrix sm (data, ridx, cidx, nr, nc);

which creates the matrix given in section *note Storage of Sparse
Matrices::.  Note that the compressed matrix format is not used at the
time of the creation of the matrix itself, but is used internally.

   As discussed in the chapter on Sparse Matrices, the values of the
sparse matrix are stored in increasing column-major ordering.  Although
the data passed by the user need not respect this requirement,
pre-sorting the data will significantly speed up creation of the sparse
matrix.

   The disadvantage of this technique for creating a sparse matrix is
that there is a brief time when two copies of the data exist.  For
extremely memory constrained problems this may not be the best technique
for creating a sparse matrix.

   The alternative is to first create a sparse matrix with the desired
number of non-zero elements and then later fill those elements in.
Sample code:

     int nz = 4, nr = 3, nc = 4;
     SparseMatrix sm (nr, nc, nz);
     sm(0,0) = 1; sm(0,1) = 2; sm(1,3) = 3; sm(2,3) = 4;

   This creates the same matrix as previously.  Again, although not
strictly necessary, it is significantly faster if the sparse matrix is
created and the elements are added in column-major ordering.  The reason
for this is that when elements are inserted at the end of the current
list of known elements then no element in the matrix needs to be moved
to allow the new element to be inserted; Only the column indexes need to
be updated.

   There are a few further points to note about this method of creating
a sparse matrix.  First, it is possible to create a sparse matrix with
fewer elements than are actually inserted in the matrix.  Therefore,

     int nz = 4, nr = 3, nc = 4;
     SparseMatrix sm (nr, nc, 0);
     sm(0,0) = 1; sm(0,1) = 2; sm(1,3) = 3; sm(2,3) = 4;

is perfectly valid.  However, it is a very bad idea because as each new
element is added to the sparse matrix the matrix needs to request more
space and reallocate memory.  This is an expensive operation, that will
significantly slow this means of creating a sparse matrix.  Furthermore,
it is possible to create a sparse matrix with too much storage, so
having NZ greater than 4 is also valid.  The disadvantage is that the
matrix occupies more memory than strictly needed.

   It is not always possible to know the number of non-zero elements
prior to filling a matrix.  For this reason the additional unused
storage of a sparse matrix can be removed after its creation with the
'maybe_compress' function.  In addition, 'maybe_compress' can deallocate
the unused storage, but it can also remove zero elements from the
matrix.  The removal of zero elements from the matrix is controlled by
setting the argument of the 'maybe_compress' function to be 'true'.
However, the cost of removing the zeros is high because it implies
re-sorting the elements.  If possible, it is better if the user does not
add the unnecessary zeros in the first place.  An example of the use of
'maybe_compress' is

     int nz = 6, nr = 3, nc = 4;

     SparseMatrix sm1 (nr, nc, nz);
     sm1(0,0) = 1; sm1(0,1) = 2; sm1(1,3) = 3; sm1(2,3) = 4;
     sm1.maybe_compress ();  // No zero elements were added

     SparseMatrix sm2 (nr, nc, nz);
     sm2(0,0) = 1; sm2(0,1) = 2; sm(0,2) = 0; sm(1,2) = 0;
     sm1(1,3) = 3; sm1(2,3) = 4;
     sm2.maybe_compress (true);  // Zero elements were added

   The use of the 'maybe_compress' function should be avoided if
possible as it will slow the creation of the matrix.

   A third means of creating a sparse matrix is to work directly with
the data in compressed row format.  An example of this technique might
be

     octave_value arg;
     ...
     int nz = 6, nr = 3, nc = 4;   // Assume we know the max # nz
     SparseMatrix sm (nr, nc, nz);
     Matrix m = arg.matrix_value ();

     int ii = 0;
     sm.cidx (0) = 0;
     for (int j = 1; j < nc; j++)
       {
         for (int i = 0; i < nr; i++)
           {
             double tmp = foo (m(i,j));
             if (tmp != 0.)
               {
                 sm.data(ii) = tmp;
                 sm.ridx(ii) = i;
                 ii++;
               }
           }
         sm.cidx(j+1) = ii;
      }
     sm.maybe_compress ();  // If don't know a-priori the final # of nz.

which is probably the most efficient means of creating a sparse matrix.

   Finally, it might sometimes arise that the amount of storage
initially created is insufficient to completely store the sparse matrix.
Therefore, the method 'change_capacity' exists to reallocate the sparse
memory.  The above example would then be modified as

     octave_value arg;
     ...
     int nz = 6, nr = 3, nc = 4;   // Assume we know the max # nz
     SparseMatrix sm (nr, nc, nz);
     Matrix m = arg.matrix_value ();

     int ii = 0;
     sm.cidx (0) = 0;
     for (int j = 1; j < nc; j++)
       {
         for (int i = 0; i < nr; i++)
           {
             double tmp = foo (m(i,j));
             if (tmp != 0.)
               {
                 if (ii == nz)
                   {
                     nz += 2;   // Add 2 more elements
                     sm.change_capacity (nz);
                   }
                 sm.data(ii) = tmp;
                 sm.ridx(ii) = i;
                 ii++;
               }
           }
         sm.cidx(j+1) = ii;
      }
     sm.maybe_mutate ();  // If don't know a-priori the final # of nz.

   Note that both increasing and decreasing the number of non-zero
elements in a sparse matrix is expensive as it involves memory
reallocation.  Also as parts of the matrix, though not its entirety,
exist as old and new copies at the same time, additional memory is
needed.  Therefore, if possible this should be avoided.


File: octave.info,  Node: Using Sparse Matrices in Oct-Files,  Prev: Creating Sparse Matrices in Oct-Files,  Up: Sparse Matrices in Oct-Files

A.1.6.3 Using Sparse Matrices in Oct-Files
..........................................

Most of the same operators and functions on sparse matrices that are
available from the Octave command line are also available within
oct-files.  The basic means of extracting a sparse matrix from an
'octave_value' and returning it as an 'octave_value', can be seen in the
following example.

     octave_value_list retval;

     SparseMatrix sm = args(0).sparse_matrix_value ();
     SparseComplexMatrix scm =
         args(1).sparse_complex_matrix_value ();
     SparseBoolMatrix sbm = args(2).sparse_bool_matrix_value ();
     ...
     retval(2) = sbm;
     retval(1) = scm;
     retval(0) = sm;

   The conversion to an 'octave_value' is handled by the sparse
'octave_value' constructors, and so no special care is needed.


File: octave.info,  Node: Accessing Global Variables in Oct-Files,  Next: Calling Octave Functions from Oct-Files,  Prev: Sparse Matrices in Oct-Files,  Up: Oct-Files

A.1.7 Accessing Global Variables in Oct-Files
---------------------------------------------

Global variables allow variables in the global scope to be accessed.
Global variables can be accessed within oct-files by using the support
functions 'get_global_value' and 'set_global_value'.  'get_global_value'
takes two arguments, the first is a string representing the variable
name to obtain.  The second argument is a boolean argument specifying
what to do if no global variable of the desired name is found.  An
example of the use of these two functions is

     #include <octave/oct.h>

     DEFUN_DLD (globaldemo, args, , "Global Demo")
     {
       octave_value retval;
       int nargin = args.length ();

       if (nargin != 1)
         print_usage ();
       else
         {
           std::string s = args(0).string_value ();
           if (! error_state)
             {
               octave_value tmp = get_global_value (s, true);
               if (tmp.is_defined ())
                 retval = tmp;
               else
                 retval = "Global variable not found";

               set_global_value ("a", 42.0);
             }
         }
       return retval;
     }


   An example of its use is

     global a b
     b = 10;
     globaldemo ("b")
     => 10
     globaldemo ("c")
     => "Global variable not found"
     num2str (a)
     => 42


File: octave.info,  Node: Calling Octave Functions from Oct-Files,  Next: Calling External Code from Oct-Files,  Prev: Accessing Global Variables in Oct-Files,  Up: Oct-Files

A.1.8 Calling Octave Functions from Oct-Files
---------------------------------------------

There is often a need to be able to call another Octave function from
within an oct-file, and there are many examples of such within Octave
itself.  For example, the 'quad' function is an oct-file that calculates
the definite integral by quadrature over a user supplied function.

   There are also many ways in which a function might be passed.  It
might be passed as one of

  1. Function Handle

  2. Anonymous Function Handle

  3. Inline Function

  4. String

   The example below demonstrates an example that accepts all four means
of passing a function to an oct-file.

     #include <octave/oct.h>
     #include <octave/parse.h>

     DEFUN_DLD (funcdemo, args, nargout, "Function Demo")
     {
       octave_value_list retval;
       int nargin = args.length ();

       if (nargin < 2)
         print_usage ();
       else
         {
           octave_value_list newargs;
           for (octave_idx_type i = nargin - 1; i > 0; i--)
             newargs(i-1) = args(i);
           if (args(0).is_function_handle () || args(0).is_inline_function ())
             {
               octave_function *fcn = args(0).function_value ();
               if (! error_state)
                 retval = feval (fcn, newargs, nargout);
             }
           else if (args(0).is_string ())
             {
               std::string fcn = args(0).string_value ();
               if (! error_state)
                 retval = feval (fcn, newargs, nargout);
             }
           else
             error ("funcdemo: INPUT must be string, inline, or function handle");
         }
       return retval;
     }


   The first argument to this demonstration is the user-supplied
function and the remaining arguments are all passed to the user
function.

     funcdemo (@sin,1)
     => 0.84147
     funcdemo (@(x) sin (x), 1)
     => 0.84147
     funcdemo (inline ("sin (x)"), 1)
     => 0.84147
     funcdemo ("sin",1)
     => 0.84147
     funcdemo (@atan2, 1, 1)
     => 0.78540

   When the user function is passed as a string the treatment of the
function is different.  In some cases it is necessary to have the user
supplied function as an 'octave_function' object.  In that case the
string argument can be used to create a temporary function as
demonstrated below.

     std::octave fcn_name = unique_symbol_name ("__fcn__");
     std::string fcode = "function y = ";
     fcode.append (fcn_name);
     fcode.append ("(x) y = ");
     fcn = extract_function (args(0), "funcdemo", fcn_name,
                             fcode, "; endfunction");
     ...
     if (fcn_name.length ())
       clear_function (fcn_name);

   There are two important things to know in this case.  First, the
number of input arguments to the user function is fixed, and in the
above example is a single argument.  Second, to avoid leaving the
temporary function in the Octave symbol table it should be cleared after
use.  Also, by convention internal function names begin and end with the
character sequence '__'.


File: octave.info,  Node: Calling External Code from Oct-Files,  Next: Allocating Local Memory in Oct-Files,  Prev: Calling Octave Functions from Oct-Files,  Up: Oct-Files

A.1.9 Calling External Code from Oct-Files
------------------------------------------

Linking external C code to Octave is relatively simple, as the C
functions can easily be called directly from C++.  One possible issue is
that the declarations of the external C functions may need to be
explicitly defined as C functions to the compiler.  If the declarations
of the external C functions are in the header 'foo.h', then the tactic
to ensure that the C++ compiler treats these declarations as C code is

     #ifdef __cplusplus
     extern "C"
     {
     #endif
     #include "foo.h"
     #ifdef __cplusplus
     }  /* end extern "C" */
     #endif

   Calling Fortran code, however, can pose more difficulties.  This is
due to differences in the manner in which compilers treat the linking of
Fortran code with C or C++ code.  Octave supplies a number of macros
that allow consistent behavior across a number of compilers.

   The underlying Fortran code should use the 'XSTOPX' function to
replace the Fortran 'STOP' function.  'XSTOPX' uses the Octave exception
handler to treat failing cases in the Fortran code explicitly.  Note
that Octave supplies its own replacement BLAS 'XERBLA' function, which
uses 'XSTOPX'.

   If the code calls 'XSTOPX', then the 'F77_XFCN' macro should be used
to call the underlying Fortran function.  The Fortran exception state
can then be checked with the global variable
'f77_exception_encountered'.  If 'XSTOPX' will not be called, then the 'F77_FCN'
macro should be used instead to call the Fortran code.

   There is no great harm in using 'F77_XFCN' in all cases, except that
for Fortran code that is short running and executes a large number of
times, there is potentially an overhead in doing so.  However, if 'F77_FCN'
is used with code that calls 'XSTOP', Octave can generate a segmentation
fault.

   An example of the inclusion of a Fortran function in an oct-file is
given in the following example, where the C++ wrapper is

     #include <octave/oct.h>
     #include <octave/f77-fcn.h>

     extern "C"
     {
       F77_RET_T
       F77_FUNC (fortsub, FORTSUB)
         (const int&, double*, F77_CHAR_ARG_DECL F77_CHAR_ARG_LEN_DECL);
     }

     DEFUN_DLD (fortdemo, args, , "Fortran Demo")
     {
       octave_value_list retval;
       int nargin = args.length ();

       if (nargin != 1)
         print_usage ();
       else
         {
           NDArray a = args(0).array_value ();
           if (! error_state)
             {
               double *av = a.fortran_vec ();
               octave_idx_type na = a.numel ();
               OCTAVE_LOCAL_BUFFER (char, ctmp, 128);

               F77_XFCN (fortsub, FORTSUB,
                         (na, av, ctmp F77_CHAR_ARG_LEN (128)));

               retval(1) = std::string (ctmp);
               retval(0) = a;
             }
         }
       return retval;
     }


and the Fortran function is

           subroutine fortsub (n, a, s)
           implicit none
           character*(*) s
           real*8 a(*)
           integer*4 i, n, ioerr
           do i = 1, n
             if (a(i) .eq. 0d0) then
               call xstopx ('fortsub: divide by zero')
             else
               a(i) = 1d0 / a(i)
             endif
           enddo
           write (unit = s, fmt = '(a,i3,a,a)', iostat = ioerr)
          $       'There are ', n,
          $       ' values in the input vector', char(0)
           if (ioerr .ne. 0) then
             call xstopx ('fortsub: error writing string')
           endif
           return
           end



   This example demonstrates most of the features needed to link to an
external Fortran function, including passing arrays and strings, as well
as exception handling.  Both the Fortran and C++ files need to be
compiled in order for the example to work.

     mkoctfile fortdemo.cc fortsub.f
     [b, s] = fortdemo (1:3)
     =>
       b = 1.00000   0.50000   0.33333
       s = There are   3 values in the input vector
     [b, s] = fortdemo (0:3)
     error: fortdemo: fortsub: divide by zero

