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

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

END-INFO-DIR-ENTRY

   Copyright © 1996-2018 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: Image Processing,  Next: Audio Processing,  Prev: Signal Processing,  Up: Top

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

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

     I = imread ("myimage.jpg");
     S = conv2 (I, ones (5, 5) / 25, "same");
     [Dx, Dy] = gradient (S);

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

* Menu:

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


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

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

The first step in most image processing tasks is to load an image into
Octave which is done with the ‘imread’ function.  The ‘imwrite’ function
is the corresponding function for writing images to the disk.

   In summary, most image processing code will follow the structure of
this code

     I = imread ("my_input_image.img");
     J = process_my_image (I);
     imwrite (J, "my_output_image.img");

 -- : [IMG, MAP, ALPHA] = imread (FILENAME)
 -- : [...] = imread (URL)
 -- : [...] = imread (..., EXT)
 -- : [...] = imread (..., IDX)
 -- : [...] = imread (..., PARAM1, VALUE1, ...)
     Read images from various file formats.

     Read an image as a matrix from the file FILENAME or from the online
     resource URL.  If neither is given, but EXT was specified, look for
     a file with the extension EXT.

     The size and class of the output depends on the format of the
     image.  A color image is returned as an MxNx3 matrix.  Grayscale
     and black-and-white images are of size MxN.  Multipage images will
     have an additional 4th dimension.

     The bit depth of the image determines the class of the output:
     "uint8", "uint16", or "single" for grayscale and color, and
     "logical" for black-and-white.  Note that indexed images always
     return the indexes for a colormap, independent of whether MAP is a
     requested output.  To obtain the actual RGB image, use ‘ind2rgb’.
     When more than one indexed image is being read, MAP is obtained
     from the first.  In some rare cases this may be incorrect and
     ‘imfinfo’ can be used to obtain the colormap of each image.

     See the Octave manual for more information in representing images.

     Some file formats, such as TIFF and GIF, are able to store multiple
     images in a single file.  IDX can be a scalar or vector specifying
     the index of the images to read.  By default, Octave will read only
     the first page.

     Depending on the file format, it is possible to configure the
     reading of images with PARAMETER, VALUE pairs.  The following
     options are supported:

     "Frames" or "Index"
          This is an alternative method to specify IDX.  When specifying
          it in this way, its value can also be the string "all".

     "Info"
          This option exists for MATLAB compatibility, but has no
          effect.  For maximum performance when reading multiple images
          from a single file, use the "Index" option.

     "PixelRegion"
          Controls the image region that is read.  The value must be a
          cell array with two arrays of 3 elements ‘{[ROWS], [COLS]}’.
          The elements in the array are the start, increment, and end
          pixel to be read.  If the increment value is omitted it
          defaults to 1.  For example, the following are all equivalent:

               imread (filename, "PixelRegion", {[200 600], [300 700]});
               imread (filename, "PixelRegion", {[200 1 600], [300 1 700]});
               imread (filename)(200:600, 300:700);

     See also: *note imwrite: XREFimwrite, *note imfinfo: XREFimfinfo,
     *note imformats: XREFimformats.

 -- : imwrite (IMG, FILENAME)
 -- : imwrite (IMG, FILENAME, EXT)
 -- : imwrite (IMG, MAP, FILENAME)
 -- : imwrite (..., PARAM1, VAL1, ...)
     Write images in various file formats.

     The image IMG can be a binary, grayscale, RGB, or multi-dimensional
     image.  The size and class of IMG should be the same as what should
     be expected when reading it with ‘imread’: the 3rd and 4th
     dimensions reserved for color space, and multiple pages
     respectively.  If it’s an indexed image, the colormap MAP must also
     be specified.

     If EXT is not supplied, the file extension of FILENAME is used to
     determine the format.  The actual supported formats are dependent
     on options made during the build of Octave.  Use ‘imformats’ to
     check the support of the different image formats.

     Depending on the file format, it is possible to configure the
     writing of images with PARAM, VAL pairs.  The following options are
     supported:

     ‘Alpha’
          Alpha (transparency) channel for the image.  This must be a
          matrix with same class, and number of rows and columns of IMG.
          In case of a multipage image, the size of the 4th dimension
          must also match and the third dimension must be a singleton.
          By default, image will be completely opaque.

     ‘Compression’
          Compression to use one the image.  Can be one of the
          following: "none" (default), "bzip", "fax3", "fax4", "jpeg",
          "lzw", "rle", or "deflate".  Note that not all compression
          types are available for all image formats in which it defaults
          to your Magick library.

     ‘DelayTime’
          For formats that accept animations (such as GIF), controls for
          how long a frame is displayed until it moves to the next one.
          The value must be scalar (which will applied to all frames in
          IMG), or a vector of length equal to the number of frames in
          IM.  The value is in seconds, must be between 0 and 655.35,
          and defaults to 0.5.

     ‘DisposalMethod’
          For formats that accept animations (such as GIF), controls
          what happens to a frame before drawing the next one.  Its
          value can be one of the following strings: "doNotSpecify"
          (default); "leaveInPlace"; "restoreBG"; and "restorePrevious",
          or a cell array of those string with length equal to the
          number of frames in IMG.

     ‘LoopCount’
          For formats that accept animations (such as GIF), controls how
          many times the sequence is repeated.  A value of Inf means an
          infinite loop (default), a value of 0 or 1 that the sequence
          is played only once (loops zero times), while a value of 2 or
          above loops that number of times (looping twice means it plays
          the complete sequence 3 times).  This option is ignored when
          there is only a single image at the end of writing the file.

     ‘Quality’
          Set the quality of the compression.  The value should be an
          integer between 0 and 100, with larger values indicating
          higher visual quality and lower compression.  Defaults to 75.

     ‘WriteMode’
          Some file formats, such as TIFF and GIF, are able to store
          multiple images in a single file.  This option specifies if
          IMG should be appended to the file (if it exists) or if a new
          file should be created for it (possibly overwriting an
          existing file).  The value should be the string "Overwrite"
          (default), or "Append".

          Despite this option, the most efficient method of writing a
          multipage image is to pass a 4 dimensional IMG to ‘imwrite’,
          the same matrix that could be expected when using ‘imread’
          with the option "Index" set to "all".

     See also: *note imread: XREFimread, *note imfinfo: XREFimfinfo,
     *note imformats: XREFimformats.

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

     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 EXEC_PATH: XREFEXEC_PATH, *note OCTAVE_HOME:
     XREFOCTAVE_HOME, *note OCTAVE_EXEC_HOME: XREFOCTAVE_EXEC_HOME.

   It is possible to get information about an image file on disk,
without actually reading it into Octave.  This is done using the
‘imfinfo’ function which provides read access to many of the parameters
stored in the header of the image file.

 -- : INFO = imfinfo (FILENAME)
 -- : INFO = imfinfo (URL)
 -- : INFO = imfinfo (..., EXT)
     Read image information from a file.

     ‘imfinfo’ returns a structure containing information about the
     image stored in the file FILENAME.  If there is no file FILENAME,
     and EXT was specified, it will look for a file named FILENAME and
     extension EXT, i.e., a file named FILENAME.EXT.

     The output structure INFO contains the following fields:

     ‘Filename’
          The full name of the image file.

     ‘FileModDate’
          Date of last modification to the file.

     ‘FileSize’
          Number of bytes of the image on disk

     ‘Format’
          Image format (e.g., "jpeg").

     ‘Height’
          Image height in pixels.

     ‘Width’
          Image Width in pixels.

     ‘BitDepth’
          Number of bits per channel per pixel.

     ‘ColorType’
          Image type.  Value is "grayscale", "indexed", "truecolor",
          "CMYK", or "undefined".

     ‘XResolution’
          X resolution of the image.

     ‘YResolution’
          Y resolution of the image.

     ‘ResolutionUnit’
          Units of image resolution.  Value is "Inch", "Centimeter", or
          "undefined".

     ‘DelayTime’
          Time in 1/100ths of a second (0 to 65535) which must expire
          before displaying the next image in an animated sequence.

     ‘LoopCount’
          Number of iterations to loop an animation.

     ‘ByteOrder’
          Endian option for formats that support it.  Value is
          "little-endian", "big-endian", or "undefined".

     ‘Gamma’
          Gamma level of the image.  The same color image displayed on
          two different workstations may look different due to
          differences in the display monitor.

     ‘Quality’
          JPEG/MIFF/PNG compression level.  Value is an integer in the
          range [0 100].

     ‘DisposalMethod’
          Only valid for GIF images, control how successive frames are
          rendered (how the preceding frame is disposed of) when
          creating a GIF animation.  Values can be "doNotSpecify",
          "leaveInPlace", "restoreBG", or "restorePrevious".  For
          non-GIF files, value is an empty string.

     ‘Chromaticities’
          Value is a 1x8 Matrix with the x,y chromaticity values for
          white, red, green, and blue points, in that order.

     ‘Comment’
          Image comment.

     ‘Compression’
          Compression type.  Value can be "none", "bzip", "fax3",
          "fax4", "jpeg", "lzw", "rle", "deflate", "lzma", "jpeg2000",
          "jbig2", "jbig2", or "undefined".

     ‘Colormap’
          Colormap for each image.

     ‘Orientation’
          The orientation of the image with respect to the rows and
          columns.  Value is an integer between 1 and 8 as defined in
          the TIFF 6 specifications, and for MATLAB compatibility.

     ‘Software’
          Name and version of the software or firmware of the camera or
          image input device used to generate the image.

     ‘Make’
          The manufacturer of the recording equipment.  This is the
          manufacture of the DSC, scanner, video digitizer or other
          equipment that generated the image.

     ‘Model’
          The model name or model number of the recording equipment as
          mentioned on the field "Make".

     ‘DateTime’
          The date and time of image creation as defined by the Exif
          standard, i.e., it is the date and time the file was changed.

     ‘ImageDescription’
          The title of the image as defined by the Exif standard.

     ‘Artist’
          Name of the camera owner, photographer or image creator.

     ‘Copyright’
          Copyright notice of the person or organization claiming rights
          to the image.

     ‘DigitalCamera’
          A struct with information retrieved from the Exif tag.

     ‘GPSInfo’
          A struct with geotagging information retrieved from the Exif
          tag.

     See also: *note imread: XREFimread, *note imwrite: XREFimwrite,
     *note imshow: XREFimshow, *note imformats: XREFimformats.

   By default, Octave’s image IO functions (‘imread’, ‘imwrite’, and
‘imfinfo’) use the ‘GraphicsMagick’ library for their operations.  This
means a vast number of image formats is supported but considering the
large amount of image formats in science and its commonly closed nature,
it is impossible to have a library capable of reading them all.  Because
of this, the function ‘imformats’ keeps a configurable list of available
formats, their extensions, and what functions should the image IO
functions use.  This allows one to expand Octave’s image IO capabilities
by creating functions aimed at acting on specific file formats.

   While it would be possible to call the extra functions directly,
properly configuring Octave with ‘imformats’ allows one to keep a
consistent code that is abstracted from file formats.

   It is important to note that a file format is not actually defined by
its file extension and that ‘GraphicsMagick’ is capable to read and
write more file formats than the ones listed by ‘imformats’.  What this
means is that even with an incorrect or missing extension the image may
still be read correctly, and that even unlisted formats are not
necessarily unsupported.

 -- : imformats ()
 -- : FORMATS = imformats (EXT)
 -- : FORMATS = imformats (FORMAT)
 -- : FORMATS = imformats ("add", FORMAT)
 -- : FORMATS = imformats ("remove", EXT)
 -- : FORMATS = imformats ("update", EXT, FORMAT)
 -- : FORMATS = imformats ("factory")
     Manage supported image formats.

     FORMATS is a structure with information about each supported file
     format, or from a specific format EXT, the value displayed on the
     field ‘ext’.  It contains the following fields:

     ext
          The name of the file format.  This may match the file
          extension but Octave will automatically detect the file
          format.

     description
          A long description of the file format.

     isa
          A function handle to confirm if a file is of the specified
          format.

     write
          A function handle to write if a file is of the specified
          format.

     read
          A function handle to open files the specified format.

     info
          A function handle to obtain image information of the specified
          format.

     alpha
          Logical value if format supports alpha channel (transparency
          or matte).

     multipage
          Logical value if format supports multipage (multiple images
          per file).

     It is possible to change the way Octave manages file formats with
     the options "add", "remove", and "update", and supplying a
     structure FORMAT with the required fields.  The option "factory"
     resets the configuration to the default.

     This can be used by Octave packages to extend the image reading
     capabilities Octave, through use of the PKG_ADD and PKG_DEL
     commands.

     See also: *note imfinfo: XREFimfinfo, *note imread: XREFimread,
     *note imwrite: XREFimwrite.


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.

 -- : imshow (IM)
 -- : imshow (IM, LIMITS)
 -- : imshow (IM, MAP)
 -- : imshow (RGB, ...)
 -- : imshow (FILENAME)
 -- : imshow (..., STRING_PARAM1, VALUE1, ...)
 -- : 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 filename 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.

     "colormap"
          VALUE1 is the colormap to use when displaying an indexed
          image.

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

 -- : image (IMG)
 -- : image (X, Y, IMG)
 -- : image (..., "PROP", VAL, ...)
 -- : image ("PROP1", VAL1, ...)
 -- : 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.

     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.

     Graphic Properties: The full list of properties is documented at
     *note Image Properties: Image Properties.

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

 -- : imagesc (IMG)
 -- : imagesc (X, Y, IMG)
 -- : imagesc (..., CLIMITS)
 -- : imagesc (..., "PROP", VAL, ...)
 -- : imagesc ("PROP1", VAL1, ...)
 -- : imagesc (HAX, ...)
 -- : 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.

 -- : im2double (IMG)
 -- : im2double (IMG, "indexed")
     Convert image to double precision.

     The conversion of IMG to double precision, is dependent on the type
     of input image.  The following input classes are supported:

     ‘uint8, uint16, and int16’
          The range of values from the class is scaled to the interval
          [0 1].

     ‘logical’
          True and false values are assigned a value of 0 and 1
          respectively.

     ‘single’
          Values are cast to double.

     ‘double’
          Returns the same image.

     If IMG is an indexed image, then the second argument should be the
     string "indexed".  If so, then IMG must either be of floating point
     class, or unsigned integer class and it will simply be cast to
     double.  If it is an integer class, a +1 offset is applied.

     See also: *note double: XREFdouble.

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

     A colormap is a real matrix, of class single or double, with 3
     columns.  Each row represents a single color.  The 3 columns
     contain red, green, and blue intensities respectively.

     All values in a colormap should be in the [0 1] range but this is
     not enforced.  Each function must decide what to do for values
     outside this range.

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

 -- : IMG = gray2ind (I)
 -- : IMG = gray2ind (I, N)
 -- : IMG = gray2ind (BW)
 -- : IMG = gray2ind (BW, N)
 -- : [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.

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

 -- : [X, MAP] = rgb2ind (RGB)
 -- : [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 color
     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 color
     channels as separate variables.

     See also: *note ind2rgb: XREFind2rgb, *note rgb2hsv: XREFrgb2hsv,
     *note rgb2gray: XREFrgb2gray.

 -- : RGB = ind2rgb (X, MAP)
 -- : [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.

 -- : FRAME = getframe ()
 -- : FRAME = getframe (HAX)
 -- : FRAME = getframe (HFIG)
 -- : FRAME = getframe (..., RECT)

     Capture a figure or axes as a movie frame structure.

     Without an argument, capture the current axes excluding ticklabels,
     title, and x/y/zlabels.  The returned structure FRAME has a field
     ‘cdata’, which contains the actual image data in the form of an
     NxMx3 (RGB) uint8 matrix, and a field ‘colormap’ which is provided
     for MATLAB compatibility but is always empty.

     If the first argument HAX is an axes handle, then capture this
     axes, rather than the current axes returned by ‘gca’.

     If the first argument HFIG is a figure handle then the entire
     corresponding figure canvas is captured.

     Finally, if a second argument RECT is provided it must be a
     four-element vector ([left bottom width height]) defining the
     region inside the figure to be captured.  Regardless of the figure
     "units" property, RECT must be defined in *pixels*.

     See also: *note im2frame: XREFim2frame, *note frame2im:
     XREFframe2im.

 -- : [X, MAP] = frame2im (FRAME)
     Convert movie frame to indexed image.

     A movie frame is simply a struct with the fields "cdata" and
     "colormap".

     Support for N-dimensional images or movies is given when FRAME is a
     struct array.  In such cases, X will be a MxNx1xK or MxNx3xK for
     indexed and RGB movies respectively, with each frame concatenated
     along the 4th dimension.

     See also: *note im2frame: XREFim2frame, *note getframe:
     XREFgetframe.

 -- : im2frame (RGB)
 -- : im2frame (X, MAP)
     Convert image to movie frame.

     A movie frame is simply a struct with the fields "cdata" and
     "colormap".

     Support for N-dimensional images is given when each image
     projection, matrix sizes of MxN and MxNx3 for RGB images, is
     concatenated along the fourth dimension.  In such cases, the
     returned value is a struct array.

     See also: *note frame2im: XREFframe2im.

 -- : CMAP = colormap ()
 -- : CMAP = colormap (MAP)
 -- : CMAP = colormap ("default")
 -- : CMAP = colormap (MAP_NAME)
 -- : CMAP = colormap (HAX, ...)
 -- : colormap MAP_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 ‘viridis’
     map with 64 entries).  The default colormap is returned.

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

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

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

     The list of built-in colormaps is:

     Map         Description
     --------------------------------------------------------------------------
     viridis     default
     jet         colormap traversing blue, cyan, green, yellow, red.
     cubehelix   colormap traversing black, blue, green, red, white with
                 increasing intensity.
     hsv         cyclic colormap traversing Hue, Saturation, Value space.
     rainbow     colormap traversing red, yellow, blue, green, violet.
     ————-       ———————————————————————————————
     hot         colormap traversing black, red, orange, yellow, white.
     cool        colormap traversing cyan, purple, magenta.
     spring      colormap traversing magenta to yellow.
     summer      colormap traversing green to yellow.
     autumn      colormap traversing red, orange, yellow.
     winter      colormap traversing blue to green.
     ————-       ———————————————————————————————
     gray        colormap traversing black to white in shades of gray.
     bone        colormap traversing black, gray-blue, white.
     copper      colormap traversing black to light copper.
     pink        colormap traversing black, gray-pink, white.
     ocean       colormap traversing black, dark-blue, white.
     ————-       ———————————————————————————————
     colorcube   equally spaced colors in RGB color space.
     flag        cyclic 4-color map of red, white, blue, black.
     lines       cyclic colormap with colors from axes "ColorOrder"
                 property.
     prism       cyclic 6-color map of red, orange, yellow, green, blue,
                 violet.
     ————-       ———————————————————————————————
     white       all white colormap (no colors).

     See also: *note viridis: XREFviridis, *note jet: XREFjet, *note
     cubehelix: XREFcubehelix, *note hsv: XREFhsv, *note rainbow:
     XREFrainbow, *note hot: XREFhot, *note cool: XREFcool, *note
     spring: XREFspring, *note summer: XREFsummer, *note autumn:
     XREFautumn, *note winter: XREFwinter, *note gray: XREFgray, *note
     bone: XREFbone, *note copper: XREFcopper, *note pink: XREFpink,
     *note ocean: XREFocean, *note colorcube: XREFcolorcube, *note flag:
     XREFflag, *note lines: XREFlines, *note prism: XREFprism, *note
     white: XREFwhite.

 -- : rgbplot (CMAP)
 -- : rgbplot (CMAP, STYLE)
 -- : 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 an RGB
          component 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.

 -- : MAP = autumn ()
 -- : 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.

 -- : MAP = bone ()
 -- : 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.

 -- : MAP = colorcube ()
 -- : 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.

 -- : MAP = cool ()
 -- : 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.

 -- : MAP = copper ()
 -- : 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.

 -- : MAP = cubehelix ()
 -- : MAP = cubehelix (N)
     Create cubehelix colormap.

     This colormap varies from black to white going though blue, green,
     and red tones while maintaining a monotonically increasing
     perception of intensity.  This is achieved by traversing a color
     cube from black to white through a helix, hence the name cubehelix,
     while taking into account the perceived brightness of each channel
     according to the NTSC specifications from 1953.

          rgbplot (cubehelix (256))

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

     Reference: Green, D. A., 2011, ‘"A colour scheme for the display of
     astronomical intensity images"’, Bulletin of the Astronomical
     Society of India, 39, 289.

     See also: *note colormap: XREFcolormap.

 -- : MAP = flag ()
 -- : 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.

 -- : MAP = gray ()
 -- : 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.

 -- : MAP = hot ()
 -- : 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.

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

 -- : MAP = jet ()
 -- : 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.

 -- : MAP = lines ()
 -- : 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, orange, yellow, purple, green, light blue, and 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.

 -- : MAP = ocean ()
 -- : 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.

 -- : MAP = pink ()
 -- : MAP = pink (N)
     Create color colormap.  This colormap varies from black to white
     with shades of gray-pink.

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

 -- : MAP = prism ()
 -- : 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.

 -- : MAP = rainbow ()
 -- : 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.

 -- : MAP = spring ()
 -- : 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.

 -- : MAP = summer ()
 -- : 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.

 -- : MAP = viridis ()
 -- : MAP = viridis (N)
     Create color colormap.  This colormap ranges from dark
     purplish-blue through blue, 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.

 -- : MAP = white ()
 -- : MAP = white (N)
     Create color colormap.  This colormap is completely 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.

 -- : MAP = winter ()
 -- : 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.

 -- : CMAP = contrast (X)
 -- : 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.

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

 -- : MAP_OUT = brighten (BETA)
 -- : MAP_OUT = brighten (MAP, BETA)
 -- : MAP_OUT = brighten (H, BETA)
 -- : brighten (...)
     Brighten or darken a colormap.

     The argument BETA must be a scalar between -1 and 1, where a
     negative value darkens and a positive value brightens the 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.

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

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

 -- : spinmap ()
 -- : spinmap (T)
 -- : spinmap (T, INC)
 -- : 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.

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

     The root properties are also inverted such that all subsequent
     plots will 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 factory
     default colors.

     If the first argument HFIG is a figure handle or list of figure
     handles, then operate on these figures rather than the current
     figure returned by ‘gcf’.  The root properties will not be changed
     unless 0 is in the list of figures.

     Programming Note: ‘whitebg’ operates by changing the color
     properties of the children of the specified figures.  Only objects
     with a single color are affected.  For example, a patch with a
     single "FaceColor" will be changed, but a patch with shading
     ("interp") will not be modified.  For inversion, the new color is
     simply the inversion in RGB space: ‘CNEW = [1-R 1-G 1-B]’.  When a
     color is specified, the axes and figure are set to the new color,
     and the color of child objects are then adjusted to have some
     contrast (visibility) against the new background.

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

   The following functions can be used to manipulate colormaps.

 -- : [Y, NEWMAP] = cmunique (X, MAP)
 -- : [Y, NEWMAP] = cmunique (RGB)
 -- : [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.

 -- : [Y, NEWMAP] = cmpermute (X, MAP)
 -- : [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 the HSV color
system and vice versa.  It is also possible to convert from a color RGB
image to a grayscale image.

 -- : HSV_MAP = rgb2hsv (RGB_MAP)
 -- : HSV_IMG = rgb2hsv (RGB_IMG)
     Transform a colormap or image from RGB to HSV color 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 in a cylindrical coordinate system.  Hue is the
     azimuth and describes the dominant color.  Saturation is the radial
     distance and gives the amount of hue mixed into the color.  Value
     is the height and is the amount of light in the color.

     Output class and size will be the same as input.

     See also: *note hsv2rgb: XREFhsv2rgb, *note rgb2ind: XREFrgb2ind,
     *note rgb2gray: XREFrgb2gray.

 -- : RGB_MAP = hsv2rgb (HSV_MAP)
 -- : RGB_IMG = hsv2rgb (HSV_IMG)
     Transform a colormap or image from HSV to RGB color space.

     A color in HSV space is represented by hue, saturation and value
     (brightness) levels in a cylindrical coordinate system.  Hue is the
     azimuth and describes the dominant color.  Saturation is the radial
     distance and gives the amount of hue mixed into the color.  Value
     is the height and is the amount of light in the color.

     The input can be both a colormap or RGB image.  In the case of
     floating point input, values are expected to be on the [0 1] range.
     In the case of hue (azimuth), since the value corresponds to an
     angle, ‘mod (h, 1)’ is used.

          >> hsv2rgb ([0.5 1 1])
          ⇒ ans = 0 1 1

          >> hsv2rgb ([2.5 1 1])
          ⇒ ans = 0 1 1

          >> hsv2rgb ([3.5 1 1])
          ⇒ ans = 0 1 1

     Output class and size will be the same as input.

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

 -- : I = rgb2gray (RGB_IMG)
 -- : GRAY_MAP = rgb2gray (RGB_MAP)
     Transform an image or colormap from red-green-blue (RGB) color
     space to a grayscale intensity image.

     The input may be of class uint8, int8, uint16, int16, single, or
     double.  The output is of the same class as the input.

     Implementation Note: The grayscale intensity is calculated as

          I = 0.298936*R + 0.587043*G + 0.114021*B

     which corresponds to the luminance channel when RGB is translated
     to YIQ as documented in <https://en.wikipedia.org/wiki/YIQ>.

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


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

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

* Menu:

* Audio File Utilities::
* Audio Device Information::
* Audio Player::
* Audio Recorder::
* Audio Data Processing::


File: octave.info,  Node: Audio File Utilities,  Next: Audio Device Information,  Up: Audio Processing

33.1 Audio File Utilities
=========================

The following functions allow you to read, write and retrieve
information about audio files.  Various formats are supported including
wav, flac and ogg vorbis.

 -- : INFO = audioinfo (FILENAME)
     Return information about an audio file specified by FILENAME.

     The output INFO is a structure containing the following fields:

     ‘Filename’
          Name of the audio file.

     ‘CompressionMethod’
          Audio compression method.  Unused, only present for
          compatibility with MATLAB.

     ‘NumChannels’
          Number of audio channels.

     ‘SampleRate’
          Sample rate of the audio, in Hertz.

     ‘TotalSamples’
          Number of samples in the file.

     ‘Duration’
          Duration of the audio, in seconds.

     ‘BitsPerSample’
          Number of bits per sample.

     ‘BitRate’
          Audio bit rate.  Unused, only present for compatibility with
          MATLAB.

     ‘Title’
          "Title" audio metadata value as a string, or empty if not
          present.

     ‘Artist’
          "Artist" audio metadata value as a string, or empty if not
          present.

     ‘Comment’
          "Comment" audio metadata value as a string, or empty if not
          present.

     See also: *note audioread: XREFaudioread, *note audiowrite:
     XREFaudiowrite.

 -- : [Y, FS] = audioread (FILENAME)
 -- : [Y, FS] = audioread (FILENAME, SAMPLES)

 -- : [Y, FS] = audioread (FILENAME, DATATYPE)
 -- : [Y, FS] = audioread (FILENAME, SAMPLES, DATATYPE)
     Read the audio file FILENAME and return the audio data Y and
     sampling rate FS.

     The audio data is stored as matrix with rows corresponding to audio
     frames and columns corresponding to channels.

     The optional two-element vector argument SAMPLES specifies starting
     and ending frames.

     The optional argument DATATYPE specifies the datatype to return.
     If it is "native", then the type of data depends on how the data is
     stored in the audio file.

     See also: *note audiowrite: XREFaudiowrite, *note audioformats:
     XREFaudioformats, *note audioinfo: XREFaudioinfo.

 -- : audiowrite (FILENAME, Y, FS)
 -- : audiowrite (FILENAME, Y, FS, NAME, VALUE, ...)

     Write audio data from the matrix Y to FILENAME at sampling rate FS
     with the file format determined by the file extension.

     Additional name/value argument pairs may be used to specify the
     following options:

     ‘BitsPerSample’
          Number of bits per sample.  Valid values are 8, 16, 24, and
          32.  Default is 16.

     ‘BitRate’
          Valid argument name, but ignored.  Left for compatibility with
          MATLAB.

     ‘Quality’
          Quality setting for the Ogg Vorbis compressor.  Values can
          range between 0 and 100 with 100 being the highest quality
          setting.  Default is 75.

     ‘Title’
          Title for the audio file.

     ‘Artist’
          Artist name.

     ‘Comment’
          Comment.

     See also: *note audioread: XREFaudioread, *note audioformats:
     XREFaudioformats, *note audioinfo: XREFaudioinfo.

 -- : audioformats ()
 -- : audioformats (FORMAT)
     Display information about all supported audio formats.

     If the optional argument FORMAT is given, then display only formats
     with names that start with FORMAT.

     See also: *note audioread: XREFaudioread, *note audiowrite:
     XREFaudiowrite.


File: octave.info,  Node: Audio Device Information,  Next: Audio Player,  Prev: Audio File Utilities,  Up: Audio Processing

33.2 Audio Device Information
=============================

 -- : DEVINFO = audiodevinfo ()

 -- : DEVS = audiodevinfo (IO)
 -- : NAME = audiodevinfo (IO, ID)
 -- : ID = audiodevinfo (IO, NAME)
 -- : ID = audiodevinfo (IO, RATE, BITS, CHANS)

 -- : SUPPORTS = audiodevinfo (IO, ID, RATE, BITS, CHANS)

     Return a structure describing the available audio input and output
     devices.

     The DEVINFO structure has two fields "input" and "output".  The
     value of each field is a structure array with fields "Name",
     "DriverVersion" and "ID" describing an audio device.

     If the optional argument IO is 1, return information about input
     devices only.  If it is 0, return information about output devices
     only.  If IO is the only argument supplied, return the number of
     input or output devices available.

     If the optional argument ID is provided, return information about
     the corresponding device.

     If the optional argument NAME is provided, return the id of the
     named device.

     Given a sampling rate, bits per sample, and number of channels for
     an input or output device, return the ID of the first device that
     supports playback or recording using the specified parameters.

     If also given a device ID, return true if the device supports
     playback or recording using those parameters.


File: octave.info,  Node: Audio Player,  Next: Audio Recorder,  Prev: Audio Device Information,  Up: Audio Processing

33.3 Audio Player
=================

The following methods are used to create and use audioplayer objects.
These objects can be used to play back audio data stored in Octave
matrices and arrays.  The audioplayer object supports playback from
various devices available to the system, blocking and non-blocking
playback, convenient pausing and resuming and much more.

 -- : PLAYER = audioplayer (Y, FS)
 -- : PLAYER = audioplayer (Y, FS, NBITS)
 -- : PLAYER = audioplayer (Y, FS, NBITS, ID)
 -- : PLAYER = audioplayer (RECORDER)
 -- : PLAYER = audioplayer (RECORDER, ID)
     Create an audioplayer object that will play back data Y at sample
     rate FS.

     The optional arguments NBITS, and ID specify the bit depth and
     player device id, respectively.  Device IDs may be found using the
     audiodevinfo function.  Given an audioplayer object, use the data
     from the object to initialize the player.

     The signal Y can be a vector or a two-dimensional array.

     The following example will create an audioplayer object that will
     play back one second of white noise at 44100 sample rate using 8
     bits per sample.

          y = 0.25 * randn (2, 44100);
          player = audioplayer (y, 44100, 8);
          play (player);

* Menu:

* Playback::
* Player Properties::


File: octave.info,  Node: Playback,  Next: Player Properties,  Up: Audio Player

33.3.1 Playback
---------------

The following methods are used to control player playback.

 -- : play (PLAYER)
 -- : play (PLAYER, START)
 -- : play (PLAYER, LIMITS)
     Play audio stored in the audioplayer object PLAYER without
     blocking.

     Given optional argument start, begin playing at START samples in
     the recording.  Given a two-element vector LIMITS, begin and end
     playing at the number of samples specified by the elements of the
     vector.

 -- : playblocking (PLAYER)
 -- : playblocking (PLAYER, START)
 -- : playblocking (PLAYER, LIMITS)
     Play audio stored in the audioplayer object PLAYER with blocking.

     Given optional argument start, begin playing at START samples in
     the recording.  Given a two-element vector LIMITS, begin and end
     playing at the number of samples specified by the elements of the
     vector.

 -- : pause (PLAYER)
     Pause the audioplayer PLAYER.

 -- : resume (PLAYER)
     Resume playback for the paused audioplayer object PLAYER.

 -- : stop (PLAYER)
     Stop the playback for the audioplayer PLAYER and reset the relevant
     variables to their starting values.

 -- : isplaying (PLAYER)
     Return true if the audioplayer object PLAYER is currently playing
     back audio and false otherwise.


File: octave.info,  Node: Player Properties,  Prev: Playback,  Up: Audio Player

33.3.2 Properties
-----------------

The remaining couple of methods are used to get and set various
properties of the audioplayer object.

 -- : VALUE = get (PLAYER, NAME)
 -- : VALUES = get (PLAYER)
     Return the VALUE of the property identified by NAME.

     If NAME is a cell array return the values of the properties
     identified by the elements of the cell array.  Given only the
     player object, return a scalar structure with values of all
     properties of PLAYER.  The field names of the structure correspond
     to property names.

 -- : set (PLAYER, NAME, VALUE)
 -- : set (PLAYER, PROPERTIES)
 -- : PROPERTIES = set (PLAYER)
     Set the value of property specified by NAME to a given VALUE.

     If NAME and VALUE are cell arrays, set each property to the
     corresponding value.  Given a structure of PROPERTIES with fields
     corresponding to property names, set the value of those properties
     to the field values.  Given only the audioplayer object, return a
     structure of settable properties.


File: octave.info,  Node: Audio Recorder,  Next: Audio Data Processing,  Prev: Audio Player,  Up: Audio Processing

33.4 Audio Recorder
===================

The following methods are used to create and use audiorecorder objects.
These objects can be used to record audio data from various devices
available to the system.  You can use convenient methods to retrieve
that data or audioplayer objects created from that data.  Methods for
blocking and non-blocking recording, pausing and resuming recording and
much more is available.

 -- : RECORDER = audiorecorder ()
 -- : RECORDER = audiorecorder (FS, NBITS, CHANNELS)
 -- : RECORDER = audiorecorder (FS, NBITS, CHANNELS, ID)
     Create an audiorecorder object recording 8 bit mono audio at 8000
     Hz sample rate.

     The optional arguments FS, NBITS, CHANNELS, and ID specify the
     sample rate, bit depth, number of channels and recording device id,
     respectively.  Device IDs may be found using the audiodevinfo
     function.

* Menu:

* Recording::
* Data Retrieval::
* Recorder Properties::


File: octave.info,  Node: Recording,  Next: Data Retrieval,  Up: Audio Recorder

33.4.1 Recording
----------------

The following methods control the recording process.

 -- : record (RECORDER)
 -- : record (RECORDER, LENGTH)
     Record audio without blocking using the audiorecorder object
     RECORDER until stopped or paused by the STOP or PAUSE method.

     Given the optional argument LENGTH, record for LENGTH seconds.

 -- : recordblocking (RECORDER, LENGTH)
     Record audio with blocking (synchronous I/O).

     The length of the recording in seconds (LENGTH) must be specified.

 -- : pause (RECORDER)
     Pause recording with audiorecorder object RECORDER.

 -- : resume (RECORDER)
     Resume recording with the paused audiorecorder object RECORDER.

 -- : stop (RECORDER)
     Stop the audiorecorder object RECORDER and clean up any audio
     streams.

 -- : isrecording (RECORDER)
     Return true if the audiorecorder object RECORDER is currently
     recording audio and false otherwise.


File: octave.info,  Node: Data Retrieval,  Next: Recorder Properties,  Prev: Recording,  Up: Audio Recorder

33.4.2 Data Retrieval
---------------------

The following methods allow you to retrieve recorded audio data in
various ways.

 -- : DATA = getaudiodata (RECORDER)
 -- : DATA = getaudiodata (RECORDER, DATATYPE)
     Return recorder audio data as a matrix with values between -1.0 and
     1.0 and with as many columns as there are channels in the recorder.

     Given the optional argument DATATYPE, convert the recorded data to
     the specified type, which may be one of "double", "single",
     "int16", "int8" or "uint8".

 -- : PLAYER = getplayer (RECORDER)
     Return an audioplayer object with data recorded by the
     audiorecorder object RECORDER.

 -- : PLAYER = play (RECORDER)
 -- : PLAYER = play (RECORDER, START)
 -- : PLAYER = play (RECORDER, [START, END])
     Play the audio recorded in RECORDER and return a corresponding
     audioplayer object.

     If the optional argument START is provided, begin playing START
     seconds in to the recording.

     If the optional argument END is provided, stop playing at END
     seconds in the recording.


File: octave.info,  Node: Recorder Properties,  Prev: Data Retrieval,  Up: Audio Recorder

33.4.3 Properties
-----------------

The remaining two methods allow you to read or alter the properties of
audiorecorder objects.

 -- : VALUE = get (RECORDER, NAME)
 -- : VALUES = get (RECORDER)
     Return the VALUE of the property identified by NAME.

     If NAME is a cell array, return the values of the properties
     corresponding to the elements of the cell array.  Given only the
     recorder object, return a scalar structure with values of all
     properties of RECORDER.  The field names of the structure
     correspond to property names.

 -- : set (RECORDER, NAME, VALUE)
 -- : set (RECORDER, PROPERTIES)
 -- : PROPERTIES = set (RECORDER)
     Set the value of property specified by NAME to a given VALUE.

     If NAME and VALUE are cell arrays of the same size, set each
     property to a corresponding value.  Given a structure with fields
     corresponding to property names, set the value of those properties
     to the corresponding field values.  Given only the recorder object,
     return a structure of settable properties.


File: octave.info,  Node: Audio Data Processing,  Prev: Audio Recorder,  Up: Audio Processing

33.5 Audio Data 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’.

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

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

 -- : record (SEC)
 -- : record (SEC, FS)
     Record SEC seconds of audio from the system’s default audio input
     at a sampling rate of 8000 samples per second.

     If the optional argument FS is given, it specifies the sampling
     rate for recording.

     For more control over audio recording, use the ‘audiorecorder’
     class.

     See also: *note sound: XREFsound, *note soundsc: XREFsoundsc.

 -- : sound (Y)
 -- : sound (Y, FS)
 -- : sound (Y, FS, NBITS)
     Play audio data Y at sample rate FS to the default audio device.

     The audio signal Y can be a vector or a two-column array,
     representing mono or stereo audio, respectively.

     If FS is not given, a default sample rate of 8000 samples per
     second is used.

     The optional argument NBITS specifies the bit depth to play to the
     audio device and defaults to 8 bits.

     For more control over audio playback, use the ‘audioplayer’ class.

     See also: *note soundsc: XREFsoundsc, *note record: XREFrecord.

 -- : soundsc (Y)
 -- : soundsc (Y, FS)
 -- : soundsc (Y, FS, NBITS)
 -- : soundsc (..., [YMIN, YMAX])
     Scale the audio data Y and play it at sample rate FS to the default
     audio device.

     The audio signal Y can be a vector or a two-column array,
     representing mono or stereo audio, respectively.

     If FS is not given, a default sample rate of 8000 samples per
     second is used.

     The optional argument NBITS specifies the bit depth to play to the
     audio device and defaults to 8 bits.

     By default, Y is automatically normalized to the range [-1, 1].  If
     the range [YMIN, YMAX] is given, then elements of Y that fall
     within the range YMIN ≤ Y ≤ YMAX are scaled to the range [-1, 1]
     instead.

     For more control over audio playback, use the ‘audioplayer’ class.

     See also: *note sound: XREFsound, *note record: XREFrecord.


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

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

Octave has the ability to create user-defined classes—including the
capabilities of operator and function overloading.  Classes can protect
internal properties so that they may not be altered accidentally which
facilitates data encapsulation.  In addition, rules can be created to
address the issue of class precedence in mixed class operations.

   This chapter discusses the means of constructing a user class, how to
query and set the properties of a class, and how to overload operators
and functions.  Throughout this chapter real code examples are given
using a class designed for polynomials.

* Menu:

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


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

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

This chapter illustrates user-defined classes and object oriented
programming through a custom class designed for polynomials.  This class
was chosen for its simplicity which does not distract unnecessarily from
the discussion of the programming features of Octave.  Even so, a bit of
background on the goals of the polynomial class is necessary before the
syntax and techniques of Octave object oriented programming are
introduced.

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

   This is a sufficient specification to begin writing the constructor
for the polynomial class.  All object oriented classes in Octave must be
located in a directory that is the name of the class prepended with the
‘@’ symbol.  For example, the polynomial class will have all of its
methods defined in the ‘@polynomial’ directory.

   The constructor for the class must be the name of the class itself;
in this example the constructor resides in the file
‘@polynomial/polynomial.m’.  Ideally, even when the constructor is
called with no arguments it should return a valid object.  A constructor
for the polynomial class might look like

     ## -*- texinfo -*-
     ## @deftypefn  {} {} polynomial ()
     ## @deftypefnx {} {} 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 > 1)
         print_usage ();
       endif
     
       if (nargin == 0)
         p.poly = 0;
         p = class (p, "polynomial");
       else
         if (isa (a, "polynomial"))
           p = a;
         elseif (isreal (a) && isvector (a))
           p.poly = a(:).';  # force row vector
           p = class (p, "polynomial");
         else
           error ("@polynomial: A must be a real vector");
         endif
       endif
     
     endfunction

   Note that the return value of the constructor must be the output of
the ‘class’ function.  The first argument to the ‘class’ function is a
structure and the second is the name of the class itself.  An example of
calling the class constructor to create an instance is

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

   Methods are defined by m-files in the class directory and can have
embedded documentation the same as any other m-file.  The help for the
constructor can be obtained by using the constructor name alone, that
is, for the polynomial constructor ‘help polynomial’ will return the
help string.  Help can be restricted to a particular class by using the
class directory name followed by the method.  For example, ‘help
@polynomial/polynomial’ is another way of displaying the help string for
the polynomial constructor.  This second means is the only way to obtain
help for the overloaded methods and functions of a class.

   The same specification mechanism can be used wherever Octave expects
a function name.  For example ‘type @polynomial/disp’ will print the
code of the ‘disp’ method of the polynomial class to the screen, and
‘dbstop @polynomial/disp’ will set a breakpoint at the first executable
line of the ‘disp’ method of the polynomial class.

   To check whether a variable belongs to 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

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

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

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

 -- : methods (OBJ)
 -- : methods ("CLASSNAME")
 -- : MTDS = methods (...)
     List the names of the public methods for the object OBJ or the
     named class CLASSNAME.

     OBJ may be an Octave class object or a Java object.  CLASSNAME may
     be the name of an Octave class or a Java class.

     When called with no output arguments, ‘methods’ prints the list of
     method names to the screen.  Otherwise, the output argument MTDS
     contains the list in a cell array of strings.

     See also: *note fieldnames: XREFfieldnames.

To inquire whether a particular method exists for a user class, the
‘ismethod’ function can be used.

 -- : ismethod (OBJ, METHOD)
 -- : ismethod (CLSNAME, METHOD)
     Return true if the string METHOD is a valid method of the object
     OBJ or of the class CLSNAME.

     See also: *note isprop: XREFisprop, *note isobject: XREFisobject.

For example:

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


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

34.2 Class Methods
==================

There are a number of basic class methods that can (and should) be
defined to allow the contents of the classes to be queried and set.  The
most basic of these is the ‘disp’ method.  The ‘disp’ method is used by
Octave whenever a class should be displayed on the screen.  Usually this
is the result of an Octave expression that doesn’t end with a semicolon.
If this method is not defined, then Octave won’t print anything when
displaying the contents of a class which can be confusing.

An example of a ‘disp’ method for the polynomial class might be

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

   To be consistent with the Octave graphic handle classes, a class
should also define the ‘get’ and ‘set’ methods.  The ‘get’ method
accepts one or two arguments.  The first argument is an object of the
appropriate class.  If no second argument is given then the method
should return a structure with all the properties of the class.  If the
optional second argument is given it should be a property name and the
specified property should be retrieved.

     function val = get (p, prop)
     
       if (nargin < 1 || nargin > 2)
         print_usage ();
       endif
     
       if (nargin == 1)
         val.poly = p.poly;
       else
         if (! ischar (prop))
           error ("@polynomial/get: PROPERTY must be a string");
         endif
     
         switch (prop)
           case "poly"
             val = p.poly;
           otherwise
             error ('@polynomial/get: invalid PROPERTY "%s"', prop);
         endswitch
       endif
     
     endfunction

Similarly, the first argument to the ‘set’ method should be an object
and any additional arguments should be property/value pairs.

     function pout = set (p, varargin)
     
       if (numel (varargin) < 2 || rem (numel (varargin), 2) != 0)
         error ("@polynomial/set: expecting PROPERTY/VALUE pairs");
       endif
     
       pout = p;
       while (numel (varargin) > 1)
         prop = varargin{1};
         val  = varargin{2};
         varargin(1:2) = [];
         if (! ischar (prop) || ! strcmp (prop, "poly"))
           error ("@polynomial/set: invalid PROPERTY for polynomial class");
         elseif (! (isreal (val) && isvector (val)))
           error ("@polynomial/set: VALUE must be a real vector");
         endif
     
         pout.poly = val(:).';  # force row vector
       endwhile
     
     endfunction

Note that Octave does not implement pass by reference; Therefore, to
modify an object requires an assignment statement using the return value
from the ‘set’ method.

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

The ‘set’ method makes use of the ‘subsasgn’ method of the class, and
therefore this method must also be defined.  The ‘subsasgn’ method is
discussed more thoroughly in the next section (*note Indexing
Objects::).

   Finally, user classes can be considered to be a special type of a
structure, and 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 contain a field that it
doesn’t make 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.

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

 -- : 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: Class Methods,  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 or braces, either like
‘OBJ(IDX)’ or like ‘OBJ{IDX}’, or even like ‘OBJ(IDX).FIELD’.  However,
it is up to the programmer to decide what this indexing actually means.
In the case of the 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.

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

     The subscript IDX must 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 first two 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, this class uses the convention that indexing with "()"
evaluates the polynomial and indexing with "{}" returns the N-th
coefficient (of the N-th power).  The code for the ‘subsref’ method
looks like

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

   The equivalent functionality for subscripted assignments uses the
‘subsasgn’ method.

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

     The subscript IDX must 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, *note optimize_subsasgn_calls:
     XREFoptimize_subsasgn_calls.

 -- : VAL = optimize_subsasgn_calls ()
 -- : OLD_VAL = optimize_subsasgn_calls (NEW_VAL)
 -- : 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 the ‘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.

     See also: *note subsasgn: XREFsubsasgn.

   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 there must be an ‘end’ method defined.  For example, the
‘end’ method for the 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.  An example using the
polynomial class is then

     p = polynomial ([1,2,3,4]);
     p{end-1}
       ⇒ 3

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

 -- : IDX = subsindex (OBJ)
     Convert an object to an index vector.

     When OBJ 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 were

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

     then the ‘subsindex’ function

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

     could 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 be used like ranges by providing a ‘colon’
method.

 -- : R = colon (BASE, LIMIT)
 -- : R = colon (BASE, INCREMENT, LIMIT)
     Return the result of the colon expression corresponding to BASE,
     LIMIT, and optionally, INCREMENT.

     This function is equivalent to the operator syntax ‘BASE : LIMIT’
     or ‘BASE : INCREMENT : LIMIT’.

     See also: *note linspace: XREFlinspace.


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 the
following call to ‘subsasgn’

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

where 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.  In other words,
a constant-time operation is degraded 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 a direct
‘subsasgn’ call as shown above), i.e., ‘x(1) = 1’, AND if the ‘subsasgn’
method is declared with identical input and output arguments, as 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’ will exist in the caller’s scope, it
is _solely_ the callee’s responsibility to not leave ‘x’ in an invalid
state if an error occurs during 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 way to avoid the
optimization 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 this allows an
object-specific version of a function to be called as needed.  A
pertinent example for the polynomial class might be to overload the
‘polyval’ function.

     function [y, dy] = polyval (p, varargin)
     
       if (nargout > 1)
         [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 of an overloaded function for the
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, polyval (p, x), varargin{:});
       else
         plot (x, polyval (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 for overloading are the
class conversion functions such as ‘double’.  Overloading these
functions allows the ‘cast’ function to work with a user class.  It can
also aid in the use of a class object with methods and functions from
other classes since the object can be transformed to the requisite input
form for the new function.  An example ‘double’ function for the
polynomial class might look like

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

Table 34.1: Available overloaded operators and their corresponding class
method

   An example ‘mtimes’ method for the polynomial class might look like

     function p = mtimes (a, b)
       p = 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 the
situation can easily arise where these functions are called with objects
of different classes.  It is therefore necessary to determine the
precedence of which method from 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

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

     See also: *note inferiorto: XREFinferiorto.

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

     See also: *note superiorto: XREFsuperiorto.

   With the 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 the return type should be "polynomial" and
so the ‘superiorto’ function is used in the class constructor.  In
particular the polynomial class constructor would be modified to

     ## -*- texinfo -*-
     ## @deftypefn  {} {} polynomial ()
     ## @deftypefnx {} {} 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 > 1)
         print_usage ();
       endif
     
       if (nargin == 0)
         p.poly = [0];
         p = class (p, "polynomial");
       else
         if (strcmp (class (a), "polynomial"))
           p = a;
         elseif (isreal (a) && isvector (a))
           p.poly = a(:).';  # force row vector
           p = class (p, "polynomial");
         else
           error ("@polynomial: A must be a real vector");
         endif
       endif
     
       superiorto ("double");
     
     endfunction

   Note that user classes _always_ have higher precedence than built-in
Octave types.  Thus, marking the polynomial class higher than the
"double" class is not actually necessary.

   When confronted with two objects of equal precedence, Octave will use
the method of the object that appears first in the list of arguments.


File: octave.info,  Node: Inheritance and Aggregation,  Next: classdef Classes,  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 structure 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 structure.  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 most easily demonstrated by example.  Suppose the programmer
needs a FIR filter, i.e., a filter with a numerator polynomial but a
denominator of 1.  In traditional Octave programming this would be
performed as follows.

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

   The equivalent behavior can be implemented as a class ‘@FIRfilter’.
The constructor for this class is the file ‘FIRfilter.m’ in the class
directory ‘@FIRfilter’.

     ## -*- texinfo -*-
     ## @deftypefn  {} {} FIRfilter ()
     ## @deftypefnx {} {} FIRfilter (@var{p})
     ## Create a FIR filter with polynomial @var{p} as coefficient vector.
     ## @end deftypefn
     
     function f = FIRfilter (p)
     
       if (nargin > 1)
         print_usage ();
       endif
     
       if (nargin == 0)
         p = @polynomial ([1]);
       elseif (! isa (p, "polynomial"))
         error ("@FIRfilter: P must be a polynomial object");
       endif
     
       f.polynomial = [];
       f = class (f, "FIRfilter", p);
     
     endfunction

   As before, the leading comments provide documentation for the class
constructor.  This constructor is very similar to the polynomial class
constructor, except that a polynomial object is passed as the third
argument to the ‘class’ function, telling Octave that the ‘FIRfilter’
class will be derived from the polynomial class.  The FIR filter class
itself does not have any data fields, but it must provide a struct to
the ‘class’ function.  Given that the ‘@polynomial’ constructor will add
an element named POLYNOMIAL to the object struct, the ‘@FIRfilter’ just
initializes a struct with a dummy field POLYNOMIAL which will later be
overwritten.

   Note that the sample code always provides for the case in which no
arguments are supplied.  This is important because Octave will call a
constructor with no arguments when loading objects from saved files in
order to determine the inheritance structure.

   A class may be a child of more than one class (*note class:
XREFclass.), 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.

   For the ‘FIRfilter’ class, more control about the object display is
desired.  Therefore, the ‘display’ method rather than the ‘disp’ method
is overloaded (*note Class Methods::).  A simple example might be

     function display (f)
       printf ("%s.polynomial", inputname (1));
       disp (f.polynomial);
     endfunction

   Note that the ‘FIRfilter’’s display method relies on the ‘disp’
method from the ‘polynomial’ class to actually display the filter
coefficients.  Furthermore, note that in the ‘display’ method it makes
sense to start the method with the line ‘printf ("%s =", inputname (1))’
to be consistent with the rest of Octave which prints the variable name
to be displayed followed by the value.  In general it is not recommended
to overload the ‘display’ function.

 -- : display (OBJ)
     Display the contents of the object OBJ prepended by its name.

     The Octave interpreter calls the ‘display’ function whenever it
     needs to present a class on-screen.  Typically, this would be a
     statement which does not end in a semicolon to suppress output.
     For example:

          myclass (...)

     Or:

          myobj = myclass (...)

     In general, user-defined classes should overload the ‘disp’ method
     to avoid the default output:

          myobj = myclass (...)
            ⇒ myobj =

            <class myclass>

     When overloading the ‘display’ method instead, one has to take care
     of properly displaying the object’s name.  This can be done by
     using the ‘inputname’ function.

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

   Once a constructor and display method exist, it is possible to create
an instance of the class.  It is also possible to check the class type
and examine the underlying structure.

     octave:1> f = FIRfilter (polynomial ([1 1 1]/3))
     f.polynomial = 0.33333 + 0.33333 * X + 0.33333 * 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 =

       scalar structure containing the fields:

     polynomial = 0.33333 + 0.33333 * X + 0.33333 * X ^ 2

   The only thing remaining to make this class usable is a method for
processing data.  But before that, it is usually desirable to also have
a way of changing the data stored in a class.  Since the fields in the
underlying struct are private by default, it is necessary to provide a
mechanism to access the fields.  The ‘subsref’ method may be used for
both tasks.

     function r = subsref (f, x)
     
       switch (x.type)
     
         case "()"
           n = f.polynomial;
           r = filter (n.poly, 1, x.subs{1});
     
         case "."
           fld = x.subs;
           if (! strcmp (fld, "polynomial"))
             error ('@FIRfilter/subsref: invalid property "%s"', fld);
           endif
           r = f.polynomial;
     
         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.33333 + 0.33333 * X + 0.33333 * X ^ 2

   In order to change the contents of the object a ‘subsasgn’ method is
needed.  For example, the following code makes the polynomial field
publicly writable

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

so that

     octave:1> f = FIRfilter ();
     octave:2> 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 a FIRfilter object may be used any place that a polynomial
object may be used.  This is not a normal use of a filter.  It may be a
more sensible design approach to use aggregation rather than
inheritance.  In this case, the polynomial is simply a field in the
class structure.  A class constructor for the aggregation case might be

     ## -*- texinfo -*-
     ## @deftypefn  {} {} FIRfilter ()
     ## @deftypefnx {} {} FIRfilter (@var{p})
     ## Create a FIR filter with polynomial @var{p} as coefficient vector.
     ## @end deftypefn
     
     function f = FIRfilter (p)
     
       if (nargin > 1)
         print_usage ();
       endif
     
       if (nargin == 0)
         f.polynomial = @polynomial ([1]);
       else
         if (! isa (p, "polynomial"))
           error ("@FIRfilter: P must be a polynomial object");
         endif
     
         f.polynomial = p;
       endif
     
       f = class (f, "FIRfilter");
     
     endfunction

   For this example only the constructor needs changing, and all other
class methods stay the same.


File: octave.info,  Node: classdef Classes,  Prev: Inheritance and Aggregation,  Up: Object Oriented Programming

34.6 ‘classdef’ Classes
=======================

Since version 4.0, Octave has limited support for ‘classdef’ classes.
In contrast to the aforementioned classes, called “old style classes” in
this section, ‘classdef’ classes can be defined within a single m-file.
Other innovations of ‘classdef’ classes are:

   • access rights for properties and methods,

   • static methods, i.e., methods that are independent of an object,
     and

   • the distinction between value and handle classes.

   Several features have to be added in future versions of Octave to be
fully compatible to MATLAB.  An overview of what is missing can be found
at <https://wiki.octave.org/Classdef>.

* Menu:

* Creating a classdef Class::
* Properties::
* Methods::
* Inheritance::
* Value Classes vs. Handle Classes::


File: octave.info,  Node: Creating a classdef Class,  Next: Properties,  Up: classdef Classes

34.6.1 Creating a ‘classdef’ Class
----------------------------------

A very basic ‘classdef’ value class (*note Value Classes vs. Handle
Classes::) is defined by:

     classdef some_class
       properties
       endproperties

       methods
       endmethods
     endclassdef

   In contrast to old style classes, the ‘properties’-‘endproperties’
block as well as the ‘methods’-‘endmethods’ block can be used to define
properties and methods of the class.  Because both blocks are empty,
they can be omitted in this particular case.

   For simplicity, a more advanced implementation of a ‘classdef’ class
is shown using the ‘polynomial’ example again (*note Creating a
Class::):

     classdef polynomial2
       properties
         poly = 0;
       endproperties
     
       methods
         function p = polynomial2 (a)
           if (nargin > 1)
             print_usage ();
           endif
     
           if (nargin == 1)
             if (isa (a, "polynomial2"))
               p.poly = a.poly;
             elseif (isreal (a) && isvector (a))
               p.poly = a(:).';  # force row vector
             else
               error ("polynomial2: A must be a real vector");
             endif
           endif
         endfunction
     
         function disp (p)
           a = p.poly;
           first = true;
           for i = 1 : length (a);
             if (a(i) != 0)
               if (first)
                 first = false;
               elseif (a(i) > 0 || isnan (a(i)))
                 printf (" +");
               endif
               if (a(i) < 0)
                 printf (" -");
               endif
               if (i == 1)
                 printf (" %.5g", abs (a(i)));
               elseif (abs (a(i)) != 1)
                 printf (" %.5g *", abs (a(i)));
               endif
               if (i > 1)
                 printf (" X");
               endif
               if (i > 2)
                 printf (" ^ %d", i - 1);
               endif
             endif
           endfor
     
           if (first)
             printf (" 0");
           endif
           printf ("\n");
         endfunction
       endmethods
     endclassdef

An object of class ‘polynomial2’ is created by calling the class
constructor:

     >> p = polynomial2 ([1, 0, 1])
     ⇒ p =

      1 + X ^ 2


File: octave.info,  Node: Properties,  Next: Methods,  Prev: Creating a classdef Class,  Up: classdef Classes

34.6.2 Properties
-----------------

All class properties must be defined within ‘properties’ blocks.  The
definition of a default value for a property is optional and can be
omitted.  The default initial value for each class property is ‘[]’.

   A ‘properties’ block can have additional attributes to specify access
rights or to define constants:

     classdef some_class
       properties (Access = MODE)
         PROP1
       endproperties

       properties (SetAccess = MODE, GetAccess = MODE)
         PROP2
       endproperties

       properties (Constant = true)
         PROP3 = pi ()
       endproperties

       properties
         PROP4 = 1337
       endproperties
     endclassdef

where MODE can be one of:

‘public’
     The properties can be accessed from everywhere.

‘private’
     The properties can only be accessed from class methods.  Subclasses
     of that class cannot access them.

‘protected’
     The properties can only be accessed from class methods and from
     subclasses of that class.

   When creating an object of ‘some_class’, PROP1 has the default value
‘[]’ and reading from and writing to PROP1 is defined by a single MODE.
For PROP2 the read and write access can be set differently.  Finally,
PROP3 is a constant property which can only be initialized once within
the ‘properties’ block.

   By default, in the example PROP4, properties are not constant and
have public read and write access.


File: octave.info,  Node: Methods,  Next: Inheritance,  Prev: Properties,  Up: classdef Classes

34.6.3 Methods
--------------

All class methods must be defined within ‘methods’ blocks.  An exception
to this rule is described at the end of this subsection.  Those
‘methods’ blocks can have additional attributes specifying the access
rights or whether the methods are static, i.e., methods that can be
called without creating an object of that class.

     classdef some_class
       methods
         function obj = some_class ()
           disp ("New instance created.");
         endfunction

         function disp (obj)
           disp ("Here is some_class.");
         endfunction
       endmethods

       methods (Access = MODE)
         function r = func (obj, r)
           r = 2 * r;
         endfunction
       endmethods

       methods (Static = true)
         function c = circumference (radius)
           c = 2 * pi () .* radius;
         endfunction
       endmethods
     endclassdef

   The constructor of the class is declared in the ‘methods’ block and
must have the same name as the class and exactly one output argument
which is an object of its class.

   It is also possible to overload built-in or inherited methods, like
the ‘disp’ function in the example above to tell Octave how objects of
‘some_class’ should be displayed (*note Class Methods::).

   In general, the first argument in a method definition is always the
object that it is called from.  Class methods can either be called by
passing the object as the first argument to that method or by calling
the object followed by a dot ("‘.’") and the method’s name with
subsequent arguments:

     >> obj = some_class ();
     New instance created.
     >> disp (obj);   # both are
     >> obj.disp ();  # equal

   In ‘some_class’, the method ‘func’ is defined within a ‘methods’
block setting the ‘Access’ attribute to MODE, which is one of:

‘public’
     The methods can be accessed from everywhere.

‘private’
     The methods can only be accessed from other class methods.
     Subclasses of that class cannot access them.

‘protected’
     The methods can only be accessed from other class methods and from
     subclasses of that class.

The default access for methods is ‘public’.

   Finally, the method ‘circumference’ is defined in a static ‘methods’
block and can be used without creating an object of ‘some_class’.  This
is useful for methods, that do not depend on any class properties.  The
class name and the name of the static method, separated by a dot
("‘.’"), call this static method.  In contrast to non-static methods,
the object is not passed as first argument even if called using an
object of ‘some_class’.

     >> some_class.circumference (3)
     ⇒ ans =  18.850
     >> obj = some_class ();
     New instance created.
     >> obj.circumference (3)
     ⇒ ans =  18.850

   Additionally, class methods can be defined as functions in a folder
of the same name as the class prepended with the ‘@’ symbol (*note
Creating a Class::).  The main ‘classdef’ file has to be stored in this
class folder as well.


File: octave.info,  Node: Inheritance,  Next: Value Classes vs. Handle Classes,  Prev: Methods,  Up: classdef Classes

34.6.4 Inheritance
------------------

Classes can inherit from other classes.  In this case all properties and
methods of the superclass are inherited to the subclass, considering
their access rights.  Use this syntax to inherit from ‘superclass’:

     classdef subclass < superclass
       ...
     endclassdef


File: octave.info,  Node: Value Classes vs. Handle Classes,  Prev: Inheritance,  Up: classdef Classes

34.6.5 Value Classes vs. Handle Classes
---------------------------------------

There are two intrinsically different types of ‘classdef’ classes, whose
major difference is the behavior regarding variable assignment.  The
first type are value classes:

     classdef value_class
       properties
         prop1
       endproperties

       methods
         function obj = set_prop1 (obj, val)
           obj.prop1 = val;
         endfunction
       endmethods
     endclassdef

Assigning an object of that class to another variable essentially
creates a new object:

     >> a = value_class ();
     >> a.prop1 = 1;
     >> b = a;
     >> b.prop1 = 2;
     >> b.prop1
     ⇒ ans =  2
     >> a.prop1
     ⇒ ans =  1

   But that also means that you might have to assign the output of a
method that changes properties back to the object manually:

     >> a = value_class ();
     >> a.prop1 = 1;
     >> a.set_prop1 (3);
     ⇒ ans =

     <object value_class>

     >> ans.prop1
     ⇒ ans =  3
     >> a.prop1
     ⇒ ans =  1

   The second type are handle classes.  Those classes have to be derived
from the abstract ‘handle’ class:

     classdef handle_class < handle
       properties
         prop1
       endproperties

       methods
         function set_prop1 (obj, val)
           obj.prop1 = val;
         endfunction
       endmethods
     endclassdef

   In the following example, the variables ‘a’ and ‘b’ refer to the very
same object of class ‘handle_class’:

     >> a = handle_class ();
     >> a.prop1 = 1;
     >> b = a;
     >> b.prop1 = 2;
     >> b.prop1
     ⇒ ans =  2
     >> a.prop1
     ⇒ ans =  2

   Object properties that are modified by a method of an handle class
are changed persistently:

     >> a.set_prop1 (3);
     >> a.prop1
     ⇒ ans =  3


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 features for constructing graphical interfaces that
interact with users.

   The GUI elements available are I/O dialogs, a progress bar, and UI
elements for plot windows.  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.  The various UI
elements can be used to fully customize the plot window with menubars,
context menus,

   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::
* UI Elements::
* 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 filename.

 -- : DIRNAME = uigetdir ()
 -- : DIRNAME = uigetdir (INIT_PATH)
 -- : 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.

 -- : [FNAME, FPATH, FLTIDX] = uigetfile ()
 -- : [...] = uigetfile (FLT)
 -- : [...] = uigetfile (FLT, DIALOG_NAME)
 -- : [...] = uigetfile (FLT, DIALOG_NAME, DEFAULT_FILE)
 -- : [...] = uigetfile (..., "Position", [PX PY])
 -- : [...] = 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"})’

     A directory name or path name
          If the folder name of path name contains a trailing file
          separator, the contents of that folder will be displayed.  If
          no trailing file separator is present the parent directory is
          listed.  The substring to the right of the rightmost file
          separator (if any) will be interpreted as a file or directory
          name and if that file or directory exists it will be
          highlighted.  If the path name or directory name is wholly or
          partly nonexistent, the current working directory will be
          displayed.  No filter will be active.

     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.

 -- : [FNAME, FPATH, FLTIDX] = uiputfile ()
 -- : [FNAME, FPATH, FLTIDX] = uiputfile (FLT)
 -- : [FNAME, FPATH, FLTIDX] = uiputfile (FLT, DIALOG_NAME)
 -- : [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.

   Additionally, there are dialog boxes for printing further help,
warnings or errors and to get textual input from the user.

 -- : H = errordlg ()
 -- : H = errordlg (MSG)
 -- : H = errordlg (MSG, TITLE)
 -- : H = errordlg (MSG, TITLE, CREATEMODE)
     Display an error dialog box with error message MSG and caption
     TITLE.

     The default error message is "This is the default error string."
     and the default caption is "Error Dialog".

     The error message may have multiple lines separated by newline
     characters ("\n"), or it may be a cellstr array with one element
     for each line.

     The return value H is always 1.

     Compatibility Note: The optional argument CREATEMODE is accepted
     for MATLAB compatibility, but is not implemented.  See ‘msgbox’ for
     details.

     Examples:

          errordlg ("Some fancy error occurred.");
          errordlg ("Some fancy error\nwith two lines.");
          errordlg ({"Some fancy error", "with two lines."});
          errordlg ("Some fancy error occurred.", "Fancy caption");

     See also: *note helpdlg: XREFhelpdlg, *note inputdlg: XREFinputdlg,
     *note listdlg: XREFlistdlg, *note msgbox: XREFmsgbox, *note
     questdlg: XREFquestdlg, *note warndlg: XREFwarndlg.

 -- : H = helpdlg ()
 -- : H = helpdlg (MSG)
 -- : H = helpdlg (MSG, TITLE)
     Display a help dialog box with help message MSG and caption TITLE.

     The default help message is "This is the default help string."  and
     the default caption is "Help Dialog".

     The help message may have multiple lines separated by newline
     characters ("\n"), or it may be a cellstr array with one element
     for each line.

     The return value H is always 1.

     Examples:

          helpdlg ("Some helpful text for the user.");
          helpdlg ("Some helpful text\nwith two lines.");
          helpdlg ({"Some helpful text", "with two lines."});
          helpdlg ("Some helpful text for the user.", "Fancy caption");

     See also: *note errordlg: XREFerrordlg, *note inputdlg:
     XREFinputdlg, *note listdlg: XREFlistdlg, *note msgbox: XREFmsgbox,
     *note questdlg: XREFquestdlg, *note warndlg: XREFwarndlg.

 -- : CSTR = inputdlg (PROMPT)
 -- : CSTR = inputdlg (PROMPT, TITLE)
 -- : CSTR = inputdlg (PROMPT, TITLE, ROWSCOLS)
 -- : CSTR = inputdlg (PROMPT, TITLE, ROWSCOLS, DEFAULTS)
 -- : CSTR = inputdlg (PROMPT, TITLE, ROWSCOLS, DEFAULTS, OPTIONS)
     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.

     OPTIONS
          Not supported, only for MATLAB compatibility.

     Example:

          prompt = {"Width", "Height", "Depth"};
          defaults = {"1.10", "2.20", "3.30"};
          rowscols = [1,10; 2,20; 3,30];
          dims = inputdlg (prompt, "Enter Box Dimensions", rowscols, defaults);

     See also: *note errordlg: XREFerrordlg, *note helpdlg: XREFhelpdlg,
     *note listdlg: XREFlistdlg, *note msgbox: XREFmsgbox, *note
     questdlg: XREFquestdlg, *note warndlg: XREFwarndlg.

 -- : [SEL, OK] = listdlg (KEY, VALUE, ...)
     Return user inputs from a list dialog box in a vector of selection
     indices (SEL) and a flag indicating how the user closed the dialog
     box (OK).

     The indices in SEL are 1-based.

     The value of OK is 1 if the user closed the box with the OK button,
     otherwise it is 0 and SEL is empty.

     Input 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 with the contents 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:

          my_options = {"An item", "another", "yet another"};
          [sel, ok] = listdlg ("ListString", my_options,
                               "SelectionMode", "Multiple");
          if (ok == 1)
            disp ("You selected:");
            for i = 1:numel (sel)
              disp (sprintf ("\t%s", my_options{sel(i)}));
            endfor
          else
            disp ("You cancelled.");
          endif

     See also: *note menu: XREFmenu, *note errordlg: XREFerrordlg, *note
     helpdlg: XREFhelpdlg, *note inputdlg: XREFinputdlg, *note msgbox:
     XREFmsgbox, *note questdlg: XREFquestdlg, *note warndlg:
     XREFwarndlg.

 -- : H = msgbox (MSG)
 -- : H = msgbox (MSG, TITLE)
 -- : H = msgbox (MSG, TITLE, ICON)
 -- : H = msgbox (..., CREATEMODE)
     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.

     Compatibility Note: The optional argument CREATEMODE is accepted
     for MATLAB compatibility, but is not implemented.  A valid
     CREATEMODE is either one of the character strings "nonmodal",
     "modal", or "replace", or a structure containing a field
     "WindowStyle" with one of the three character strings.

     Examples:

          msgbox ("Some message for the user.");
          msgbox ("Some message\nwith two lines.");
          msgbox ({"Some message", "with two lines."});
          msgbox ("Some message for the user.", "Fancy caption");

          % A message dialog box with error icon
          msgbox ("Some message for the user.", "Fancy caption", "error");

     See also: *note errordlg: XREFerrordlg, *note helpdlg: XREFhelpdlg,
     *note inputdlg: XREFinputdlg, *note listdlg: XREFlistdlg, *note
     questdlg: XREFquestdlg, *note warndlg: XREFwarndlg.

 -- : BTN = questdlg (MSG)
 -- : BTN = questdlg (MSG, TITLE)
 -- : BTN = questdlg (MSG, TITLE, DEFAULT)
 -- : BTN = questdlg (MSG, TITLE, BTN1, BTN2, DEFAULT)
 -- : BTN = questdlg (MSG, TITLE, BTN1, BTN2, BTN3, DEFAULT)
     Display MSG using a question dialog box and return the caption of
     the activated button.

     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 specify the
     dialog caption.  It defaults to "Question Dialog".

     The dialog may contain two or three buttons which will all close
     the dialog.

     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.

     Examples:

          btn = questdlg ("Close Octave?", "Some fancy title", "Yes", "No", "No");
          if (strcmp (btn, "Yes"))
            exit ();
          endif

     See also: *note errordlg: XREFerrordlg, *note helpdlg: XREFhelpdlg,
     *note inputdlg: XREFinputdlg, *note listdlg: XREFlistdlg, *note
     msgbox: XREFmsgbox, *note warndlg: XREFwarndlg.

 -- : H = warndlg ()
 -- : H = warndlg (MSG)
 -- : H = warndlg (MSG, TITLE)
 -- : H = warndlg (MSG, TITLE, CREATEMODE)
     Display a warning dialog box with warning message MSG and caption
     TITLE.

     The default warning message is "This is the default warning
     string."  and the default caption is "Warning Dialog".

     The warning message may have multiple lines separated by newline
     characters ("\n"), or it may be a cellstr array with one element
     for each line.

     The return value H is always 1.

     Compatibility Note: The optional argument CREATEMODE is accepted
     for MATLAB compatibility, but is not implemented.  See ‘msgbox’ for
     details.

     Examples:

          warndlg ("Some warning text for the user.");
          warndlg ("Some warning text\nwith two lines.");
          warndlg ({"Some warning text", "with two lines."});
          warndlg ("Some warning text for the user.", "Fancy caption");

     See also: *note errordlg: XREFerrordlg, *note helpdlg: XREFhelpdlg,
     *note inputdlg: XREFinputdlg, *note listdlg: XREFlistdlg, *note
     msgbox: XREFmsgbox, *note questdlg: XREFquestdlg.

   For creating new dialog types, there is a dialog function.

 -- : H = dialog ()
 -- : H = dialog ("PROPERTY", VALUE, ...)

     Create an empty modal dialog window to which other uicontrols can
     be added.

     The dialog box is a figure object with properties as recommended
     for a dialog box.

     The default properties differing from a figure are:

     buttondownfcn
          ‘if isempty (allchild(gcbf)), close (gcbf), endif’

     colormap
          []

     color
          defaultuicontrolbackgroundcolor

     dockcontrols
          off

     handlevisibility
          callback

     integerhandle
          off

     inverthardcopy
          off

     menubar
          none

     numbertitle
          off

     paperpositionmode
          auto

     resize
          off

     windowstyle
          modal

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

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

     Example:

          ## create an empty dialog window titled "Dialog Example"
          h = dialog ("name", "Dialog Example");

          ## create a button (default style)
          b = uicontrol (h, "string", "OK",
                            "position", [10 10 150 40],
                            "callback", "delete (gcf)");

          ## wait for dialog to resume or close
          uiwait (h);

     See also: *note errordlg: XREFerrordlg, *note msgbox: XREFmsgbox,
     *note questdlg: XREFquestdlg, *note warndlg: XREFwarndlg, *note
     figure: XREFfigure, *note uiwait: XREFuiwait.


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

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

 -- : H = waitbar (FRAC)
 -- : H = waitbar (FRAC, MSG)
 -- : H = waitbar (..., "createcancelbtn", FCN, ...)
 -- : H = waitbar (..., PROP, VAL, ...)
 -- : waitbar (FRAC)
 -- : waitbar (FRAC, H)
 -- : waitbar (FRAC, H, MSG)
     Return a handle H to a new progress indicator ("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.

     A cancel button can be added to the bottom of the waitbar using the
     "createcancelbtn" property of waitbar figures.  The action to be
     executed when the user presses the button is specified using a
     string or function handle FCN.

     The appearance of the waitbar figure window can be configured by
     passing PROP/VAL 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 H of the specific waitbar to modify.

     See also: *note delete: XREFdelete.


File: octave.info,  Node: UI Elements,  Next: GUI Utility Functions,  Prev: Progress Bar,  Up: GUI Development

35.3 UI Elements
================

The ui* series of functions work best with the ‘qt’ graphics toolkit,
although some functionality is available with the ‘fltk’ toolkit.  There
is no support for the ‘gnuplot’ toolkit.

 -- : HUI = uimenu (PROPERTY, VALUE, ...)
 -- : HUI = uimenu (H, PROPERTY, VALUE, ...)
     Create a uimenu object and return a handle to it.

     If H is omitted then a top-level menu for the current figure is
     created.  If H is given then a submenu relative to H is created.

     uimenu objects have the following specific properties:

     "accelerator"
          A string containing the key combination together with CTRL to
          execute this menu entry (e.g., "x" for CTRL+x).

     "callback"
          Is the function called when this menu entry is executed.  It
          can be either a function string (e.g., "myfun"), a function
          handle (e.g., @myfun) or a cell array containing the function
          handle and arguments for the callback function (e.g., {@myfun,
          arg1, arg2}).

     "checked"
          Can be set "on" or "off".  Sets a mark at this menu entry.

     "enable"
          Can be set "on" or "off".  If disabled the menu entry cannot
          be selected and it is grayed out.

     "foregroundcolor"
          A color value setting the text color for this menu entry.

     "label"
          A string containing the label for this menu entry.  A
          "&"-symbol can be used to mark the "accelerator" character
          (e.g., "E&xit")

     "position"
          An scalar value containing the relative menu position.  The
          entry with the lowest value is at the first position starting
          from left or top.

     "separator"
          Can be set "on" or "off".  If enabled it draws a separator
          line above the current position.  It is ignored for top level
          entries.

     The full list of properties is documented at *note Uimenu
     Properties: Uimenu Properties.

     Examples:

          f = uimenu ("label", "&File", "accelerator", "f");
          e = uimenu ("label", "&Edit", "accelerator", "e");
          uimenu (f, "label", "Close", "accelerator", "q", ...
                     "callback", "close (gcf)");
          uimenu (e, "label", "Toggle &Grid", "accelerator", "g", ...
                     "callback", "grid (gca)");

     See also: *note figure: XREFfigure.

 -- : HUI = uibuttongroup (PROPERTY, VALUE, ...)
 -- : HUI = uibuttongroup (PARENT, PROPERTY, VALUE, ...)
 -- : uibuttongroup (H)

     Create a uibuttongroup object and return a handle to it.

     uibuttongroups are used to create group uicontrols.

     If PARENT is omitted then a uibuttongroup for the current figure is
     created.  If no figure is available, a new figure is created first.

     If PARENT is given then a uibuttongroup relative to PARENT is
     created.

     Any provided property value pairs will override the default values
     of the created uibuttongroup object.

     Uibuttongroup properties are documented at *note Uibuttongroup
     Properties::.

     Examples:

          % create figure and panel on it
          f = figure;
          % create a button group
          gp = uibuttongroup (f, "Position", [ 0 0.5 1 1])
          % create a buttons in the group
          b1 = uicontrol (gp, "style", "radiobutton", ...
                          "string", "Choice 1", ...
                          "Position", [ 10 150 100 50 ]);
          b2 = uicontrol (gp, "style", "radiobutton", ...
                          "string", "Choice 2", ...
                          "Position", [ 10 50 100 30 ]);
          % create a button not in the group
          b3 = uicontrol (f, "style", "radiobutton", ...
                          "string", "Not in the group", ...
                          "Position", [ 10 50 100 50 ]);

     See also: *note figure: XREFfigure, *note uipanel: XREFuipanel.

 -- : HUI = uicontextmenu (PROPERTY, VALUE, ...)
 -- : HUI = uicontextmenu (H, PROPERTY, VALUE, ...)

     Create a uicontextmenu object and return a handle to it.

     If H is omitted then a uicontextmenu for the current figure is
     created.  If no figure is available, a new figure is created first.

     If H is given then a uicontextmenu relative to H is created.

     Any provided property value pairs will override the default values
     of the created uicontextmenu object.

     Uicontextmenu properties are documented at *note Uicontextmenu
     Properties::.

     Examples:

          % create figure and uicontextmenu
          f = figure;
          c = uicontextmenu (f);

          % create menus in the context menu
          m1 = uimenu ("parent",c,"label","Menu item 1","callback","disp('menu item 1')");
          m2 = uimenu ("parent",c,"label","Menu item 2","callback","disp('menu item 2')");

          % set the context menu for the figure
          set (f, "uicontextmenu", c);

     See also: *note figure: XREFfigure, *note uimenu: XREFuimenu.

 -- : HUI = uicontrol (PROPERTY, VALUE, ...)
 -- : HUI = uicontrol (PARENT, PROPERTY, VALUE, ...)
 -- : uicontrol (H)

     Create a uicontrol object and return a handle to it.

     uicontrols are used to create simple interactive controls such as
     push buttons, checkboxes, edit and list controls.

     If PARENT is omitted then a uicontrol for the current figure is
     created.  If no figure is available, a new figure is created first.

     If PARENT is given then a uicontrol relative to PARENT is created.

     Any provided property value pairs will override the default values
     of the created uicontrol object.

     Uicontrol properties are documented at *note Uicontrol
     Properties::.

     Control of the type of uicontrol created is through the use of the
     STYLE property.  If no style property is provided, a push button
     will be created.

     Valid styles for uicontrol are:

     "checkbox"
          Create a checkbox control that allows user on/off selection.

     "edit"
          Create an edit control that allows user input of single or
          multiple lines of text.

     "listbox"
          Create a listbox control that displays a list of items and
          allows user selection of single or multiple items.

     "popupmenu"
          Create a popupmenu control that displays a list of options
          that can be selected when the user clicks on the control.

     "pushbutton"
          Create a push button control that allows user to press to
          cause an action.

     "radiobutton"
          Create a radio button control intended to be used for mutually
          exclusive input in a group of radiobutton controls.

     "slider"
          Create a slider control that allows user selection from a
          range of values by sliding knob on the control.

     "text"
          Create a static text control to display single or multiple
          lines of text.

     "togglebutton"
          Create a toggle button control that appears like a push button
          but allows the user to select between two states.

     Examples:

          % create figure and panel on it
          f = figure;
          % create a button (default style)
          b1 = uicontrol (f, "string", "A Button", "position",[10 10 150 40]);
          % create an edit control
          e1 = uicontrol (f, "style", "edit", "string", "editable text", "position",[10 60 300 40]);
          % create a checkbox
          c1 = uicontrol (f, "style", "checkbox", "string", "a checkbox", "position",[10 120 150 40]);

     See also: *note figure: XREFfigure, *note uipanel: XREFuipanel.

 -- : uipanel (PROPERTY, VALUE, ...)
 -- : uipanel (PARENT, "PROPERTY, VALUE, ...)
 -- : HUI = uipanel (...)

     Create a uipanel object.

     uipanels are used as containers to group other uicontrol objects.

     If PARENT is omitted then a uipanel for the current figure is
     created.  If no figure is available, a new figure is created first.

     If PARENT is given then a uipanel relative to PARENT is created.

     Any provided property value pairs will override the default values
     of the created uipanel object.

     Uipanel properties are documented at *note Uipanel Properties::.

     The optional return value HUI is a graphics handle to the created
     uipanel object.

     Examples:

          % create figure and panel on it
          f = figure;
          p = uipanel ("title", "Panel Title", "position", [.25 .25 .5 .5]);

          % add two buttons to the panel
          b1 = uicontrol ("parent", p, "string", "A Button", "position",[18 10 150 36]);
          b2 = uicontrol ("parent", p, "string", "Another Button", "position",[18 60 150 36]);


     See also: *note figure: XREFfigure, *note uicontrol: XREFuicontrol.

 -- : uipushtool (PROPERTY, VALUE, ...)
 -- : uipushtool (PARENT, PROPERTY, VALUE, ...)
 -- : HUI = uipushtool (...)

     Create a uipushtool object.

     uipushtools are buttons that appear on a figure toolbar.  The
     button is created with a border that is shown when the user hovers
     over the button.  An image can be set using the cdata property.

     If PARENT is omitted then a uipushtool for the current figure is
     created.  If no figure is available, a new figure is created first.
     If a figure is available, but does not contain a uitoolbar, a
     uitoolbar will be created.

     If PARENT is given then a uipushtool is created on the PARENT
     uitoolbar.

     Any provided property value pairs will override the default values
     of the created uipushtool object.

     Uipushtool properties are documented at *note Uipushtool
     Properties::.

     The optional return value HUI is a graphics handle to the created
     uipushtool object.

     Examples:

          % create figure without a default toolbar
          f = figure ("toolbar", "none");
          % create empty toolbar
          t = uitoolbar (f);
          % create a 19x19x3 black square
          img=zeros(19,19,3);
          % add pushtool button to toolbar
          b = uipushtool (t, "cdata", img);

     See also: *note figure: XREFfigure, *note uitoolbar: XREFuitoolbar,
     *note uitoggletool: XREFuitoggletool.

 -- : uitoggletool (PROPERTY, VALUE, ...)
 -- : uitoggletool (PARENT, PROPERTY, VALUE, ...)
 -- : HUI = uitoggletool (...)

     Create a uitoggletool object.

     uitoggletool are togglebuttons that appear on a figure toolbar.
     The button is created with a border that is shown when the user
     hovers over the button.  An image can be set using the cdata
     property.

     If PARENT is omitted then a uitoggletool for the current figure is
     created.  If no figure is available, a new figure is created first.
     If a figure is available, but does not contain a uitoolbar, a
     uitoolbar will be created.

     If PARENT is given then a uitoggletool is created on the PARENT
     uitoolbar.

     Any provided property value pairs will override the default values
     of the created uitoggletool object.

     Uitoggletool properties are documented at *note Uitoggletool
     Properties::.

     The optional return value HUI is a graphics handle to the created
     uitoggletool object.

     Examples:

          % create figure without a default toolbar
          f = figure ("toolbar", "none");
          % create empty toolbar
          t = uitoolbar (f);
          % create a 19x19x3 black square
          img=zeros(19,19,3);
          % add uitoggletool button to toolbar
          b = uitoggletool (t, "cdata", img);

     See also: *note figure: XREFfigure, *note uitoolbar: XREFuitoolbar,
     *note uipushtool: XREFuipushtool.

 -- : uitoolbar (PROPERTY, VALUE, ...)
 -- : uitoolbar (PARENT, PROPERTY, VALUE, ...)
 -- : HUI = uitoolbar (...)

     Create a uitoolbar object.  A uitoolbar displays uitoggletool and
     uipushtool buttons.

     If PARENT is omitted then a uitoolbar for the current figure is
     created.  If no figure is available, a new figure is created first.

     If PARENT is given then a uitoolbar relative to PARENT is created.

     Any provided property value pairs will override the default values
     of the created uitoolbar object.

     Uitoolbar properties are documented at *note Uitoolbar
     Properties::.

     The optional return value HUI is a graphics handle to the created
     uitoolbar object.

     Examples:

          % create figure without a default toolbar
          f = figure ("toolbar", "none");
          % create empty toolbar
          t = uitoolbar (f);

     See also: *note figure: XREFfigure, *note uitoggletool:
     XREFuitoggletool, *note uipushtool: XREFuipushtool.


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

35.4 GUI Utility Functions
==========================

These functions do not implement a GUI element but are useful when
developing programs that do.  The functions ‘uiwait’, ‘uiresume’, and
‘waitfor’ are only available with the ‘qt’ or ‘fltk’ toolkits.

 -- : DATA = guidata (H)
 -- : 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.

 -- : HDATA = guihandles (H)
 -- : 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.

 -- : have_window_system ()
     Return true if a window system is available (X11, Windows, or Apple
     OS X) and false otherwise.

     See also: *note isguirunning: XREFisguirunning.

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

     See also: *note have_window_system: XREFhave_window_system.

 -- : openvar (NAME)
     Open the variable NAME in the graphical Variable Editor.

 -- : uiwait
 -- : uiwait (H)
 -- : 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.

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

 -- : waitfor (H)
 -- : waitfor (H, PROP)
 -- : waitfor (H, PROP, VALUE)
 -- : 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 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.5 User-Defined Preferences
=============================

 -- : VAL = getpref ("GROUP", "PREF")
 -- : VAL = getpref ("GROUP", "PREF", DEFAULT)
 -- : {VAL1, VAL2, ...} = getpref ("GROUP", {"PREF1", "PREF2", ...})
 -- : PREFSTRUCT = getpref ("GROUP")
 -- : PREFSTRUCT = getpref ()
     Return the preference value corresponding to the named preference
     PREF in the preference group GROUP.

     The named preference group must be a string.

     If PREF does not exist in GROUP and DEFAULT is specified, create
     the preference with value DEFAULT and return DEFAULT.

     The preference PREF may be a string or cell array of strings.  If
     it is a cell array of strings then a cell array of preferences is
     returned.

     The corresponding default value DEFAULT may be any Octave value,
     .e.g., double, struct, cell array, object, etc.  Or, if PREF is a
     cell array of strings then 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.

 -- : setpref ("GROUP", "PREF", VAL)
 -- : setpref ("GROUP", {"PREF1", "PREF2", ...}, {VAL1, VAL2, ...})
     Set the preference PREF to the given VAL in the named preference
     group GROUP.

     The named preference group must be a string.

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

     The corresponding value VAL may be any Octave value, .e.g., double,
     struct, cell array, object, etc.  Or, if PREF is a cell array of
     strings then 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.

 -- : addpref ("GROUP", "PREF", VAL)
 -- : addpref ("GROUP", {"PREF1", "PREF2", ...}, {VAL1, VAL2, ...})
     Add the preference PREF and associated value VAL to the named
     preference group GROUP.

     The named preference group must be a string.

     The preference PREF may be a string or a cell array of strings.  An
     error will be issued if the preference already exists.

     The corresponding value VAL may be any Octave value, .e.g., double,
     struct, cell array, object, etc.  Or, if PREF is a cell array of
     strings then 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.

 -- : rmpref ("GROUP", "PREF")
 -- : rmpref ("GROUP", {"PREF1", "PREF2", ...})
 -- : rmpref ("GROUP")
     Remove the named preference PREF from the preference group GROUP.

     The named preference group must be a string.

     The preference PREF may be a 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.

 -- : ispref ("GROUP", "PREF")
 -- : ispref ("GROUP", {"PREF1", "PREF2", ...})
 -- : ispref ("GROUP")
     Return true if the named preference PREF exists in the preference
     group GROUP.

     The named preference group must be a string.

     The preference PREF may be a string or a cell array of 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.

 -- : prefdir
 -- : prefdir (1)
 -- : DIR = prefdir
     Return the directory that holds the preferences for Octave.

     Examples:

     Display the preferences directory

          prefdir

     Change to the preferences folder

          cd (prefdir)

     If called with an argument, the preferences directory is created if
     it doesn’t already exist.

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

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


File: octave.info,  Node: System Utilities,  Next: Packages,  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 saving time flag.

‘gmtoff’
     Seconds offset from UTC.

‘zone’
     Time zone.

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

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

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

 -- : 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\n"

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

 -- : 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
                     gmtoff = 0
                     zone = GMT
                  }

     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.

 -- : 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
                     gmtoff = -21600
                     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.

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

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

     For example:

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

     This is equivalent to ‘ctime (time ())’.

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

 -- : 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’
          Offset from UTC (±hhmm), or nothing if no time zone is
          determinable.

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

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

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

     ‘clock’ is more accurate on systems that have the ‘gettimeofday’
     function.

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

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

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

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

 -- : is_leap_year ()
 -- : 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.

 -- : tic ()
 -- : ID = tic ()
     Initialize a wall-clock timer.

     Calling ‘tic’ without an output argument resets the internal timer.
     Subsequent calls to ‘toc’ return the number of seconds since the
     timer was set.

     If called with one output argument, ‘tic’ creates a new timer
     instance and returns a timer identifier ID.  The ID is a scalar of
     type ‘uint64’ that may be passed to ‘toc’ to check elapsed time on
     this timer, rather than the default internal timer.

     Example 1 : benchmarking code with internal timer

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

     Example 2 : mixed timer id and internal timer

          tic;
          pause (1);
          toc
          ⇒ Elapsed time is 1.0089 seconds.
          id = tic;
          pause (2);
          toc (id)
          ⇒ Elapsed time is 2.01142 seconds.
          toc
          Elapsed time is 3.02308 seconds.

     Calling ‘tic’ and ‘toc’ in 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.

 -- : toc ()
 -- : toc (ID)
 -- : ELAPSED_TIME = toc (...)
     Measure elapsed time on a wall-clock timer.

     With no arguments, return the number of seconds elapsed on the
     internal timer since the last call to ‘tic’.

     When given the identifier ID of a specific timer, return the number
     of seconds elapsed since the timer ID was initialized.

     *Note tic: XREFtic, for examples of the use of ‘tic’/‘toc’.

     See also: *note tic: XREFtic, *note cputime: XREFcputime.

 -- : pause ()
 -- : pause (N)
     Suspend the execution of the program for N seconds.

     If invoked without an input arguments then the program is suspended
     until a character is typed.

     N is a positive real value and may be a fraction of a second, for
     example:

          tic; pause (0.05); toc
               ⊣ Elapsed time is 0.05039 seconds.

     The following example prints a message and then waits 5 seconds
     before clearing the screen.

          disp ("wait please...");
          pause (5);
          clc;

     See also: *note kbhit: XREFkbhit.

 -- : DAYS = datenum (DATEVEC)
 -- : DAYS = datenum (YEAR, MONTH, DAY)
 -- : DAYS = datenum (YEAR, MONTH, DAY, HOUR)
 -- : DAYS = datenum (YEAR, MONTH, DAY, HOUR, MINUTE)
 -- : DAYS = datenum (YEAR, MONTH, DAY, HOUR, MINUTE, SECOND)
 -- : DAYS = datenum ("datestr")
 -- : DAYS = datenum ("datestr", F)
 -- : DAYS = datenum ("datestr", P)
 -- : [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, F is the format string used to
     interpret date strings (see ‘datestr’).  If no format F 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.

     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.

 -- : STR = datestr (DATE)
 -- : STR = datestr (DATE, F)
 -- : 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                      3:38:09 PM
     15      HH:MM                            15:38
     16      HH:MM PM                         3: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,                    09:00
             or padded with spaces if PM is set                 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.

 -- : V = datevec (DATE)
 -- : V = datevec (DATE, F)
 -- : V = datevec (DATE, P)
 -- : V = datevec (DATE, F, P)
 -- : [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.

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

 -- : C = calendar ()
 -- : C = calendar (D)
 -- : C = calendar (Y, M)
 -- : 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.

 -- : [N, S] = weekday (D)
 -- : [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.

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

 -- : datetick ()
 -- : datetick (AXIS_STR)
 -- : datetick (DATE_FORMAT)
 -- : datetick (AXIS_STR, DATE_FORMAT)
 -- : datetick (..., "keeplimits")
 -- : datetick (..., "keepticks")
 -- : datetick (HAX, ...)
     Add date-formatted tick labels to an axis.

     The axis to apply the ticks to is determined by AXIS_STR which can
     take the values "x", "y", or "z".  The default value is "x".

     The formatting of the labels is determined by the variable
     DATE_FORMAT, which can either be a string or positive integer that
     ‘datestr’ accepts.

     If the first argument HAX is an axes handle, then plot into this
     axes, rather than the current axes returned by ‘gca’.

     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.

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

     The name F1 may contain globbing patterns, or may be a cell array
     of strings.  If F1 expands to multiple filenames, F2 must be a
     directory.

     If no destination F2 is specified then the destination is the
     present working directory.  If F2 is a filename 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.

 -- : rename OLD NEW
 -- : [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.

 -- : copyfile F1 F2
 -- : copyfile F1 F2 f
 -- : copyfile (F1, F2)
 -- : copyfile (F1, F2, 'f')
 -- : [STATUS, MSG, MSGID] = copyfile (...)
     Copy the source file(s) or directory F1 to the destination F2.

     The name F1 may contain globbing patterns, or may be a cell array
     of strings.  If F1 expands to multiple filenames, 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.

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

     See also: *note delete: XREFdelete, *note rmdir: XREFrmdir.

 -- : link OLD NEW
 -- : [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.

 -- : symlink OLD NEW
 -- : [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.

 -- : readlink SYMLINK
 -- : [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.

 -- : mkdir DIRNAME
 -- : mkdir PARENT DIRNAME
 -- : mkdir (DIRNAME)
 -- : mkdir (PARENT, DIRNAME)
 -- : [STATUS, MSG, MSGID] = mkdir (...)
     Create a directory named DIRNAME in the directory PARENT, creating
     any intermediate directories if necessary.

     If DIR is a relative path, and no PARENT directory is specified,
     then the present working directory is used.

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

     When creating a directory permissions will be set to ‘0777 -
     UMASK’.

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

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

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

     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 mkdir: XREFmkdir, *note confirm_recursive_rmdir:
     XREFconfirm_recursive_rmdir, *note pwd: XREFpwd.

 -- : VAL = confirm_recursive_rmdir ()
 -- : OLD_VAL = confirm_recursive_rmdir (NEW_VAL)
 -- : 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.

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

     MODE is interpreted as an octal number and is subject to umask
     processing.  The final calculated mode is ‘MODE - UMASK’.

     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, *note umask: XREFumask.

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

     The permission mask is a UNIX concept used when creating new
     objects on a file system such as files, directories, or named
     FIFOs.  The object to be created has base permissions in an octal
     number MODE which are modified according to the octal value of
     MASK.  The final permissions for the new object are ‘MODE - MASK’.

     See also: *note fopen: XREFfopen, *note mkdir: XREFmkdir, *note
     mkfifo: XREFmkfifo.

 -- : [INFO, ERR, MSG] = stat (FILE)
 -- : [INFO, ERR, MSG] = stat (FID)
 -- : [INFO, ERR, MSG] = lstat (FILE)
 -- : [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.

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

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

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

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

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

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

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

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

     If successful, STATUS is 1 and MSG is 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.

     If ‘attrib’ fails, MSG is a non-empty string containing an error
     message and MSG_ID is the non-empty string "fileattrib".

     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.

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

 -- : FILES = readdir (DIR)
 -- : [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.

 -- : glob (PATTERN)
     Given an array of pattern strings (as a char array or a cell array)
     in PATTERN, return a cell array of filenames 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 filenames.  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.

 -- : file_in_path (PATH, FILE)
 -- : 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
     dir_in_loadpath: XREFdir_in_loadpath, *note path: XREFpath.

 -- : filesep ()
 -- : 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.

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

     The input FILENAME is a string which is parsed.  There is no
     attempt to check whether the filename or directory specified
     actually exists.

     See also: *note fullfile: XREFfullfile, *note filesep: XREFfilesep.

 -- : FILENAME = fullfile (DIR1, DIR2, ..., FILE)
 -- : FILENAMES = fullfile (..., FILES)
     Build complete filename from separate parts.

     Joins any number of path components intelligently.  The return
     value is the concatenation of each component with exactly one file
     separator between each non empty part and at most one leading
     and/or trailing file separator.

     If the last component part is a cell array, returns a cell array of
     filepaths, one for each element in the last component, e.g.:

          fullfile ("/home/username", "data", {"f1.csv", "f2.csv", "f3.csv"})
          ⇒  /home/username/data/f1.csv
              /home/username/data/f2.csv
              /home/username/data/f3.csv

     On Windows systems, while forward slash file separators do work,
     they are replaced by backslashes; in addition drive letters are
     stripped of leading file separators to obtain a valid file path.

     Note: ‘fullfile’ does not perform any validation of the resulting
     full filename.

     See also: *note fileparts: XREFfileparts, *note filesep:
     XREFfilesep.

 -- : tilde_expand (STRING)
 -- : tilde_expand (CELLSTR)
     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.

     If the input is a cell array of strings CELLSTR then tilde
     expansion is performed on each string element.

     Examples:

          tilde_expand ("~joeuser/bin")
               ⇒ "/home/joeuser/bin"
          tilde_expand ("~/bin")
               ⇒ "/home/jwe/bin"

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

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

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

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

 -- : VAL = recycle ()
 -- : OLD_VAL = recycle (NEW_VAL)
     Query or set the preference for recycling deleted files.

     When recycling is enabled, commands which would permanently erase
     files instead move them to a temporary location (such as the
     directory labeled Trash).

     Programming Note: This function is provided for MATLAB
     compatibility, but recycling is not 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, *note rmdir: XREFrmdir.


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

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

 -- : FILELIST = bunzip2 (BZFILE)
 -- : FILELIST = bunzip2 (BZFILE, DIR)
     Unpack the bzip2 archive BZFILE.

     If DIR is specified the files are unpacked in this directory rather
     than the one where BZFILE is located.

     The optional output FILELIST is a list of the uncompressed files.

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

 -- : FILELIST = gzip (FILES)
 -- : FILELIST = gzip (FILES, DIR)
     Compress the list of files and directories specified in FILES.

     FILES is a character array or cell array of strings.  Shell
     wildcards in the filename such as ‘*’ or ‘?’ are accepted and
     expanded.  Each file is compressed separately and a new file with a
     ‘".gz"’ extension is created.  The original files are not modified,
     but existing compressed files will be silently overwritten.  If a
     directory is specified then ‘gzip’ recursively compresses all files
     in the directory.

     If DIR is defined the compressed files are placed in this
     directory, rather than the original directory where the
     uncompressed file resides.  Note that this does not replicate a
     directory tree in DIR which may lead to files overwriting each
     other if there are multiple files with the same name.

     If DIR does not exist it is created.

     The optional output FILELIST is a list of the compressed files.

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

 -- : FILELIST = gunzip (GZFILE)
 -- : FILELIST = gunzip (GZFILE, DIR)
     Unpack the gzip archive GZFILE.

     If GZFILE is a directory, all gzfiles in the directory will be
     recursively unpacked.

     If DIR is specified the files are unpacked in this directory rather
     than the one where GZFILE is located.

     The optional output FILELIST is a list of the uncompressed files.

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

 -- : FILELIST = tar (TARFILE, FILES)
 -- : FILELIST = tar (TARFILE, FILES, ROOTDIR)
     Pack the list of files and directories specified in FILES into the
     TAR archive TARFILE.

     FILES is a character array or cell array of strings.  Shell
     wildcards in the filename such as ‘*’ or ‘?’ are accepted and
     expanded.  Directories are recursively traversed and all files are
     added to the archive.

     If ROOTDIR is defined then any files without absolute pathnames are
     located relative to ROOTDIR rather than the current directory.

     The optional output FILELIST is a list of the files that were
     included in the archive.

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

 -- : untar (TARFILE)
 -- : untar (TARFILE, DIR)
     Unpack the TAR archive TARFILE.

     If DIR is specified the files are unpacked in this directory rather
     than the one where TARFILE is located.

     The optional output FILELIST is a list of the uncompressed files.

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

 -- : FILELIST = zip (ZIPFILE, FILES)
 -- : FILELIST = zip (ZIPFILE, FILES, ROOTDIR)
     Compress the list of files and directories specified in FILES into
     the ZIP archive ZIPFILE.

     FILES is a character array or cell array of strings.  Shell
     wildcards in the filename such as ‘*’ or ‘?’ are accepted and
     expanded.  Directories are recursively traversed and all files are
     compressed and added to the archive.

     If ROOTDIR is defined then any files without absolute pathnames are
     located relative to ROOTDIR rather than the current directory.

     The optional output FILELIST is a list of the files that were
     included in the archive.

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

 -- : FILELIST = unzip (ZIPFILE)
 -- : FILELIST = unzip (ZIPFILE, DIR)
     Unpack the ZIP archive ZIPFILE.

     If DIR is specified the files are unpacked in this directory rather
     than the one where ZIPFILE is located.

     The optional output FILELIST is a list of the uncompressed files.

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

 -- : FILES = unpack (FILE)
 -- : FILES = unpack (FILE, DIR)
 -- : 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.  Shell wildcards in the filename such as ‘*’ or ‘?’
     are accepted and expanded.

     If DIR is not specified or is empty (‘[]’), it defaults to the
     current directory.  If a directory is in the file list, then
     FILETYPE must also be specified.

     The specific archive filetype is inferred from the extension of the
     file.  The FILETYPE may also be specified directly using a string
     which corresponds to a known extension.

     Valid filetype extensions:

     ‘bz’
     ‘bz2’
          bzip archive

     ‘gz’
          gzip archive

     ‘tar’
          tar archive

     ‘tarbz’
     ‘tarbz2’
     ‘tbz’
     ‘tbz2’
          tar + bzip archive

     ‘targz’
     ‘tgz’
          tar + gzip archive

     ‘z’
          compress archive

     ‘zip’
          zip archive

     The optional return value is a list of FILES unpacked.

     See also: *note bunzip2: XREFbunzip2, *note gunzip: XREFgunzip,
     *note unzip: XREFunzip, *note untar: XREFuntar, *note bzip2:
     XREFbzip2, *note gzip: XREFgzip, *note zip: XREFzip, *note tar:
     XREFtar.

 -- : FILELIST = bzip2 (FILES)
 -- : FILELIST = bzip2 (FILES, DIR)
     Compress the list of files specified in FILES.

     FILES is a character array or cell array of strings.  Shell
     wildcards in the filename such as ‘*’ or ‘?’ are accepted and
     expanded.  Each file is compressed separately and a new file with a
     ‘".bz2"’ extension is created.  The original files are not
     modified, but existing compressed files will be silently
     overwritten.

     If DIR is defined the compressed files are placed in this
     directory, rather than the original directory where the
     uncompressed file resides.  Note that this does not replicate a
     directory tree in DIR which may lead to files overwriting each
     other if there are multiple files with the same name.

     If DIR does not exist it is created.

     The optional output FILELIST is a list of the compressed files.

     See also: *note bunzip2: XREFbunzip2, *note unpack: XREFunpack,
     *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::

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

 -- : F = ftp (HOST)
 -- : 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

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

     F is an FTP object returned by the ‘ftp’ function.

 -- : mget (F, FILE)
 -- : mget (F, DIR)
 -- : 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 string argument TARGET is given, then it must indicate
     the path to the local destination directory.  TARGET may be a
     relative or absolute path.

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

 -- : cd (F)
 -- : 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.

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

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

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

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

     F is an FTP object returned by the ‘ftp’ function.

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

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

     F is an FTP object returned by the ‘ftp’ function.

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

 -- : S = urlread (URL)
 -- : [S, SUCCESS] = urlread (URL)
 -- : [S, SUCCESS, MESSAGE] = urlread (URL)
 -- : [...] = 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/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.

 -- : urlwrite (URL, LOCALFILE)
 -- : F = urlwrite (URL, LOCALFILE)
 -- : [F, SUCCESS] = urlwrite (URL, LOCALFILE)
 -- : [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/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.

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

     See also: *note base64_decode: XREFbase64_decode.

 -- : X = base64_decode (S)
 -- : 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.

 -- : system ("STRING")
 -- : system ("STRING", RETURN_OUTPUT)
 -- : system ("STRING", RETURN_OUTPUT, TYPE)
 -- : [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

          [~, text] = system ("cmd");
          more on;
          disp (text);

     or

          more on;
          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.

     The shell used for executing commands varies with operating system
     and is typically ‘/bin/sh’ for UNIX systems and ‘cmd.exe’ for
     Windows systems.

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

 -- : unix ("COMMAND")
 -- : STATUS = unix ("COMMAND")
 -- : [STATUS, TEXT] = unix ("COMMAND")
 -- : [...] = unix ("COMMAND", "-echo")
     Execute a system command if running under a Unix-like operating
     system, otherwise do nothing.

     Octave waits for the external command to finish before returning
     the exit status of the program in STATUS and any output 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 ismac: XREFismac, *note ispc: XREFispc.

 -- : dos ("COMMAND")
 -- : STATUS = dos ("COMMAND")
 -- : [STATUS, TEXT] = dos ("COMMAND")
 -- : [...] = dos ("COMMAND", "-echo")
     Execute a system command if running under a Windows-like operating
     system, otherwise do nothing.

     Octave waits for the external command to finish before returning
     the exit status of the program in STATUS and any output 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 ismac: XREFismac, *note ispc: XREFispc.

 -- : open FILE
 -- : OUTPUT = open (FILE)
     Open the file FILE in Octave or in an external application based on
     the file type as determined by the filename extension.

     Recognized file types are

     ‘.m’
          Open file in the editor.

     ‘.mat’
          Load the file in the base workspace.

     ‘.exe’
          Execute the program (on Windows systems only).

     Other file types are opened in the appropriate external
     application.

 -- : OUTPUT = perl (SCRIPTFILE)
 -- : OUTPUT = perl (SCRIPTFILE, ARGUMENT1, ARGUMENT2, ...)
 -- : [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 filename it is searched for in the
     current directory and then in the Octave loadpath.

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

 -- : OUTPUT = python (SCRIPTFILE)
 -- : OUTPUT = python (SCRIPTFILE, ARGUMENT1, ARGUMENT2, ...)
 -- : [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 filename it is searched for in the
     current directory and then in the Octave loadpath.

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

 -- : FID = popen (COMMAND, MODE)
     Start a process and create a pipe.

     The name of the command to run is given by COMMAND.  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.

     The file identifier corresponding to the input or output stream of
     the process is returned in FID.

     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

     See also: *note popen2: XREFpopen2.

 -- : pclose (FID)
     Close a file identifier that was opened by ‘popen’.

     The function ‘fclose’ may also be used for the same purpose.

     See also: *note fclose: XREFfclose, *note popen: XREFpopen.

 -- : [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
     or cell 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)
              pause (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.

 -- : VAL = EXEC_PATH ()
 -- : OLD_VAL = EXEC_PATH (NEW_VAL)
 -- : 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, *note OCTAVE_EXEC_HOME: XREFOCTAVE_EXEC_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’.

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

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

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

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

     See also: *note fopen: XREFfopen, *note fclose: XREFfclose, *note
     fcntl: XREFfcntl.

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

 -- : WCONTINUE ()
     Return the numerical value of the ‘WCONTINUE’ macro.

     ‘WCONTINUE’ is 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.

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

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

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

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

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

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

 -- : WNOHANG ()
     Return the numerical value of the ‘WNOHANG’ macro.

     ‘WNOHANG’ is 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.

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

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

 -- : WUNTRACED ()
     Return the numerical value of the ‘WUNTRACED’ macro.

     ‘WUNTRACED’ is 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.

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

     See also: *note fopen: XREFfopen, *note dup2: XREFdup2.

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

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

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

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

     See also: *note getppid: XREFgetppid.

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

     See also: *note getpid: XREFgetpid.

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

     See also: *note getuid: XREFgetuid.

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

     See also: *note geteuid: XREFgeteuid.

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

     See also: *note getgid: XREFgetgid.

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

     See also: *note getegid: XREFgetegid.


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

36.7 Environment Variables
==========================

 -- : getenv (VAR)
     Return the value of the environment variable VAR.

     For example,

          getenv ("PATH")

     returns a string containing the value of your path.

     See also: *note setenv: XREFsetenv, *note unsetenv: XREFunsetenv.

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

     If no VALUE is specified then the variable will be assigned the
     null string.

     See also: *note unsetenv: XREFunsetenv, *note getenv: XREFgetenv.

 -- : STATUS = unsetenv (VAR)
     Delete the environment variable VAR.

     Return 0 if the variable was deleted, or did not exist, and -1 if
     an error occurred.

     See also: *note setenv: XREFsetenv, *note getenv: XREFgetenv.

 -- : HOMEDIR = get_home_directory ()
     Return the current home directory.

     On most systems, this is equivalent to ‘getenv ("HOME")’.  On
     Windows systems, if the environment variable ‘HOME’ is not set then
     it is equivalent to ‘fullfile (getenv ("HOMEDRIVE"), getenv
     ("HOMEPATH"))’

     See also: *note getenv: XREFgetenv.


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

36.8 Current Working Directory
==============================

 -- : cd DIR
 -- : cd
 -- : OLD_DIR = cd (DIR)
 -- : 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.

 -- : ls
 -- : ls FILENAMES
 -- : ls OPTIONS
 -- : ls OPTIONS FILENAMES
 -- : LIST = ls (...)

     List directory contents.

     The ‘ls’ command is implemented by calling the native operating
     system’s directory listing command—available OPTIONS will vary from
     system to system.

     Filenames are subject to shell expansion if they contain any
     wildcard characters ‘*’, ‘?’, ‘[]’.  To find a literal example of a
     wildcard character the wildcard must be escaped using the backslash
     operator ‘\’.

     If the optional output LIST is requested then ‘ls’ returns a
     character array with one row for each file/directory name.

     Example usage on a UNIX-like system:

          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

     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.

 -- : VAL = ls_command ()
 -- : OLD_VAL = ls_command (NEW_VAL)
     Query or set the shell command used by Octave’s ‘ls’ command.

     See also: *note ls: XREFls.

 -- : dir
 -- : dir (DIRECTORY)
 -- : [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.

     folder
          Location of file or directory

     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 ‘*’, ‘?’, ‘[]’.  To find a literal example of a wildcard
     character the wildcard must be escaped 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, *note lstat:
     XREFlstat.

 -- : pwd ()
 -- : 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.

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

     See also: *note setpwent: XREFsetpwent, *note endpwent:
     XREFendpwent.

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

     See also: *note getpwnam: XREFgetpwnam.

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

     See also: *note getpwuid: XREFgetpwuid.

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

     See also: *note getpwent: XREFgetpwent, *note endpwent:
     XREFendpwent.

 -- : endpwent ()
     Close the password database.

     See also: *note getpwent: XREFgetpwent, *note setpwent:
     XREFsetpwent.


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.

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

     See also: *note setgrent: XREFsetgrent, *note endgrent:
     XREFendgrent.

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

     See also: *note getgrnam: XREFgetgrnam.

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

     See also: *note getgrgid: XREFgetgrgid.

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

     See also: *note getgrent: XREFgetgrent, *note endgrent:
     XREFendgrent.

 -- : endgrent ()
     Close the group database.

     See also: *note getgrent: XREFgetgrent, *note setgrent:
     XREFsetgrent.


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

36.11 System Information
========================

 -- : computer ()
 -- : C = computer ()
 -- : [C, MAXSIZE] = computer ()
 -- : [C, MAXSIZE, ENDIAN] = computer ()
 -- : ARCH = computer ("arch")
     Print or return a string of the form CPU-VENDOR-OS that identifies
     the type of computer that Octave is running on.

     If invoked with an output argument, the value is returned instead
     of printed.  For example:

          computer ()
             ⊣ i586-pc-linux-gnu

          mycomp = computer ()
             ⇒ mycomp = "i586-pc-linux-gnu"

     If two output arguments are requested, also return the maximum
     number of elements for an array.  This will depend on whether
     Octave has been compiled with 32-bit or 64-bit index vectors.

     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.

     See also: *note isunix: XREFisunix, *note ismac: XREFismac, *note
     ispc: XREFispc.

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

 -- : nproc ()
 -- : 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’
          same as ‘current’, but overridable through the
          ‘OMP_NUM_THREADS’ environment variable.

 -- : ispc ()
     Return true if Octave is running on a Windows system and false
     otherwise.

     See also: *note isunix: XREFisunix, *note ismac: XREFismac.

 -- : isunix ()
     Return true if Octave is running on a Unix-like system and false
     otherwise.

     See also: *note ismac: XREFismac, *note ispc: XREFispc.

 -- : ismac ()
     Return true if Octave is running on a Mac OS X system and false
     otherwise.

     See also: *note isunix: XREFisunix, *note ispc: XREFispc.

 -- : isieee ()
     Return true if your computer _claims_ to conform to the IEEE
     standard for floating point calculations.

     No actual tests are performed.

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

 -- : isstudent ()
     Return true if running in the student edition of MATLAB.

     ‘isstudent’ always returns false in Octave.

     See also: *note false: XREFfalse.

 -- : OCTAVE_HOME ()
     Return the name of the top-level Octave installation directory.
     OCTAVE_HOME corresponds to the configuration variable PREFIX.

     See also: *note EXEC_PATH: XREFEXEC_PATH, *note IMAGE_PATH:
     XREFIMAGE_PATH, *note OCTAVE_EXEC_HOME: XREFOCTAVE_EXEC_HOME.

 -- : OCTAVE_HOME ()
     Return the name of the top-level Octave installation directory for
     architecture-dependent files.  If not specified separately, the
     value is the same as OCTAVE_HOME.  OCTAVE_EXEC_HOME corresponds to
     the configuration variable EXEC_PREFIX.

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

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

 -- : OCTAVE_VERSION ()
     Return the version number of Octave as a string.

     See also: *note ver: XREFver, *note version: XREFversion.

 -- : V = version ()
 -- : [V, D] = version ()
 -- : V = version (FEATURE)
     Get version information for Octave.

     If called without input argument, the first return value V gives
     the version number of Octave as a string.  The second return value
     D holds the release date as a string.

     The following options can be passed for FEATURE:

     "-date"
          for the release date of the running build,

     "-description"
          for a description of the release (always an empty string),

     "-release"
          for the name of the running build (always an empty string),

     "-java"
          for version information of the Java VM,

     "-fftw"
          for version information for the linked FFTW,

     "-blas"
          for version information for the linked BLAS,

     "-lapack"
          for version information for the linked LAPACK.

     "-hgid"
          the mercurial ID of the sources used to build Octave.

     The variant with no input and output argument is an alias for the
     function ‘OCTAVE_VERSION’ provided for compatibility.

     See also: *note OCTAVE_VERSION: XREFOCTAVE_VERSION, *note ver:
     XREFver.

 -- : ver
 -- : ver Octave
 -- : ver PACKAGE
 -- : v = ver (...)

     Display a header containing the current Octave version number,
     license string, and operating system.  The header is followed by a
     list of installed packages, versions, and installation directories.

     Use the package name PACKAGE or Octave to limit the listing to a
     desired component.

     When called with an output argument, 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.

     ‘Release’
          Release of the package.

     ‘Date’
          Date of the version/release.

     See also: *note version: XREFversion, *note usejava: XREFusejava,
     *note pkg: XREFpkg.

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

 -- : license
 -- : license inuse
 -- : license inuse FEATURE
 -- : license ("inuse")
 -- : RETVAL = license ("inuse")
 -- : RETVAL = license ("test", FEATURE)
 -- : RETVAL = license ("checkout", FEATURE)
 -- : [RETVAL, ERRMSG] = license ("checkout", FEATURE)
     Get license information for Octave and Octave packages.

     GNU Octave is free software distributed under the GNU General
     Public License (GPL), and a license manager makes no sense.  This
     function is provided only for MATLAB compatibility.

     When called with no extra input arguments, it returns the Octave
     license, otherwise the first input defines the operation mode and
     must be one of the following strings: ‘inuse’, ‘test’, and
     ‘checkout’.  The optional FEATURE argument can either be "octave"
     (core), or an Octave package.

     "inuse"
          Returns a list of loaded features, i.e., octave and the list
          of loaded packages.  If an output is requested, it returns a
          struct array with the fields "feature", and "user".

     "test"
          Return true if the specified FEATURE is installed, false
          otherwise.

          An optional third argument "enable" or "disable" is accepted
          but ignored.

     "checkout"
          Return true if the specified FEATURE is installed, false
          otherwise.  An optional second output will have an error
          message if a package is not installed.

     See also: *note pkg: XREFpkg, *note ver: XREFver, *note version:
     XREFversion.

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

 -- : VALUE = winqueryreg (ROOTKEY, SUBKEY, VALUENAME)
 -- : VALUE = winqueryreg (ROOTKEY, SUBKEY)
 -- : NAMES = winqueryreg (‘"name"’, ROOTKEY, SUBKEY)

     Query names or value from the Windows registry.

     On Windows, return the value of the registry key SUBKEY from the
     root key ROOTKEY.  You can specify the name of the queried registry
     value with the optional argument VALUENAME.  Otherwise, if called
     with only two arguments or VALUENAME is empty, then the default
     value of SUBKEY is returned.  If the registry value is of type
     "REG_DWORD" then VALUE is of class int32.  If the value is of the
     type "REG_SZ" or "REG_EXPAND_SZ" a string is returned.

     If the first argument is "name", a cell array of strings with the
     names of the values at that key is returned.

     The variable ROOTKEY must be a string with a valid root key
     identifier:

     HKCR
     HKEY_CLASSES_ROOT

     HKEY_CURRENT_CONFIG

     HKCU
     HKEY_CURRENT_USER

     HKLM
     HKEY_LOCAL_MACHINE

     HKU
     HKEY_USERS

     HKEY_PERFORMANCE_DATA

     Examples:

     Get a list of value names at the key ’HKCU\Environment’:

          VALUENAMES = winqueryreg ("name", "HKEY_CURRENT_USER", ...
                                    "Environment");

     For each VALUENAMES, display the value:

          for K = 1:numel (VALUENAMES)
            VAL = winqueryreg ("HKEY_CURRENT_USER", "Environment", ...
                               VALUENAMES{K});
            STR = sprintf ("%s = %s", VALUENAMES{K}, num2str (VAL));
            disp (STR);
          endfor

     On non-Windows platforms this function fails with an error.


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 ‘hash’ function to calculate hash values of
strings and files, the latter in combination with the ‘fileread’
function.  The ‘hash’ function supports the most common used
cryptographic hash functions, namely MD5 and SHA-1.

 -- : hash (HFUN, STR)
     Calculate the hash value of the string STR using the hash function
     HFUN.

     The available hash functions are given in the table below.

     ‘MD2’
          Message-Digest Algorithm 2 (RFC 1319).

     ‘MD4’
          Message-Digest Algorithm 4 (RFC 1320).

     ‘MD5’
          Message-Digest Algorithm 5 (RFC 1321).

     ‘SHA1’
          Secure Hash Algorithm 1 (RFC 3174)

     ‘SHA224’
          Secure Hash Algorithm 2 (224 Bits, RFC 3874)

     ‘SHA256’
          Secure Hash Algorithm 2 (256 Bits, RFC 6234)

     ‘SHA384’
          Secure Hash Algorithm 2 (384 Bits, RFC 6234)

     ‘SHA512’
          Secure Hash Algorithm 2 (512 Bits, RFC 6234)

     To calculate for example the MD5 hash value of the string "abc" the
     ‘hash’ function is called as follows:

          hash ("md5", "abc")
               ⊣ ans = 900150983cd24fb0d6963f7d28e17f72

     For the same string, the SHA-1 hash value is calculated with:

          hash ("sha1", "abc")
               ⊣ ans = a9993e364706816aba3e25717850c26c9cd0d89d

     And to compute the hash value of a file, e.g., ‘file = "file.txt"’,
     call ‘hash’ in combination with the ‘fileread’:

          hash ("md5", fileread (file));


File: octave.info,  Node: Packages,  Next: External Code Interface,  Prev: System Utilities,  Up: Top

37 Packages
***********

Since Octave is Free Software users are encouraged to share their
programs with others.  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 <https://octave.sourceforge.io>, 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

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

 -- : pkg COMMAND PKG_NAME
 -- : pkg COMMAND OPTION PKG_NAME
 -- : [OUT1, ...] = pkg (COMMAND, ... )
     Manage or query packages (groups of add-on functions) for Octave.

     Different actions are available depending on the value of COMMAND
     and on return arguments.

     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 file containing the package can be an url, e.g.

               pkg install 'http://somewebsite.org/image-1.0.0.tar.gz'

          installs the package found in the given url.  This requires an
          internet connection and the cURL library.

          _Security risk_: no verification of the package is performed
          before the installation.  It has the same security issues as
          manually downloading the package from the given url and
          installing it.

          _No support_: the GNU Octave community is not responsible for
          packages installed from foreign sites.  For support or for
          reporting bugs you need to contact the maintainers of the
          installed package directly (see the ‘DESCRIPTION’ file of the
          package)

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

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

               _Security risk_: no verification of the package is
               performed before the installation.  There are no
               signature for packages, or checksums to confirm the
               correct file was downloaded.  It has the same security
               issues as manually downloading the package from the
               Octave Forge repository and installing it.

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

     ‘unload’
          Remove named packages from the path.  After unloading a
          package it is no longer possible to use the functions provided
          by the package.

     ‘list’
          Show the list of currently installed packages.  For example,

               pkg list

          will produce a short report with the package name, version,
          and installation directory for each installed package.  Supply
          a package name to limit reporting to a particular package.
          For example:

               pkg list image

          If a single return argument is requested then ‘pkg’ returns a
          cell array where each element is a structure with information
          on a single package.

               installed_packages = pkg ("list")

          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 "-forge" option 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 installed packages.  With the
          option "-verbose" also list functions provided by the package.
          For example,

               pkg describe -verbose

          will describe all installed packages and the functions they
          provide.  Display can be limited to a set of packages:

               pkg describe control signal # describe control and signal packages

          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.

     See also: *note ver: XREFver, *note news: XREFnews.


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

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

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

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

