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

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

Copyright © 1996-2020 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: 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.  The full list of
     properties is documented at *note Figure Properties::.

     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.

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

     The full list of properties is 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.

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

     Create a uibuttongroup object and return a handle to it.

     A uibuttongroup is used to group uicontrol objects.

     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.

     The full list of properties is 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 ]);

     When called with a single argument H which is a handle to an
     existing uibuttongroup object, switch the focus to the specified
     uibuttongroup.  This functionality is not currently implemented.

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

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

     Create a uicontrol object and return a handle to it.

     A uicontrol object is 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.

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

     The type of uicontrol created is specified by 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]);

     When called with a single argument H which is a handle to an
     existing uicontrol object, switch the keyboard focus to the
     specified uicontrol.  As a result, the uicontrol object will
     receive keyboard events that can be processed using the
     "keypressfcn" callback.

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

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

     A uitable object is used to show tables of data in a figure window.

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

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

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

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

     Examples:

          ## Create figure and place a table on it
          f = figure ();
          m = magic (8);
          t = uitable (f, "Data", m, "ColumnWidth", { 40 });

          ## Create a table with labeled rows and columns
          f = figure ();
          d = reshape (1:9, [3, 3]);
          row_names = { "Row1", "Row2", "Row3" };
          col_names = { "Col1", "Col2", "Col3" };
          t = uitable (f, "Data", d, ...
                       "RowName", row_names, "ColumnName", col_names);

          p = get (t, "Position");
          e = get (t, "Extent");
          p(3:4) = e(3:4);
          set (t, "Position", p);

          ## Long demo with callbacks
          function uitable_demo ()
            f = figure ("Name", "uitable Demo", "Menu", "none", ...
                        "Position", [10 10 1000 680]);

            ## A basic example
            d = { "char"   , "A string";
                  "double" , 12.3456789;
                  "complex", 1+2i;
                  "bool"   , true;
                  "single" , single (12.3456789);
                  "int8"   , int8 (-128);
                  "uint8"  , uint8 (128);
                  "int16"  , int16 (-32768);
                  "uint16" , uint16 (32768);
                  "int32"  , int32 (-2147483648);
                  "uint32" , uint32 (2147483648);
                  "int64"  , int64 (-2147483649);
                  "uint64" , uint64 (2147843649)};

            popup_options = {"A", "B", "C", "D", "E"};

            columnformat_options = { "[]", "char", "pop-up", "numeric", ...
                                     "short", "short e", "short eng", ...
                                     "short g", "long", "long e", ...
                                     "long eng", "long g", "bank", "+", ...
                                     "rat", "logical"};
            columnformat_values = columnformat_options;
            columnformat_values{1} = "";
            columnformat_values{3} = popup_options;

            default_data = repmat (d(:,2), 1, columns (columnformat_options));
            b_add = uicontrol (f, "Position", [285 630 600 50], ...
                      "UserData", [rows(d), 1], ...
                      "Style", "pushbutton", ...
                      "String", "Set data at selected point to selected datatype");

            l_type_table = uicontrol (f, "Position", [ 0 603 120 25 ], ...
                "String", "Datatype Table:", ...
                "Style", "text");
            t_type_table = uitable (f, "Position", [ 0 530 1000 70 ], ...
                "Data", transpose (d(:, 2)), ...
                "ColumnName", transpose (d(:, 1)), ...
                "RowName", "Value", ...
                "CellSelectionCallback", ...
                     @(x, y) set (b_add, "UserData", y.Indices ));

            l_point_table = uicontrol (f, "Position", [ 0 640 60 25 ], ...
                "String", "Point:", ...
                "Style", "text");
            t_point_table = uitable (f, "Position", [ 80 630 160 42 ], ...
                "RowName", [], ...
                "ColumnName", {"x", "y"}, ...
                "Data", [ 1, 1 ], ...
                "ColumnEditable", true);

            l_editable_table = uicontrol (f, "Position", [ 0 502 200 25 ], ...
                "Style", "text", ...
                "String", "Set Data Columns Editable:");
            t_editable_table = ...
              uitable (f, "Position", [ 0 434 1000 65 ], ...
                          "Data", repmat (false, 1, columns (default_data)), ...
                          "ColumnEditable", true);

            l_format_table = uicontrol (f, "Position", [ 0 406 200 25 ], ...
                "Style", "text", ...
                "String", "Set Data Column Format:");
            t_format_table = ...
              uitable (f, "Position", [ 0 338 1000 65 ], ...
                          "Data", columnformat_options, ...
                          "ColumnEditable", true, ...
                          "ColumnFormat", arrayfun (@(x) {columnformat_options}, ...
                                                    1:columns (columnformat_options)));

            l_data_table = uicontrol (f, "Style", "text", ...
                                         "String", "Data:", ...
                                         "Position", [ 0 310 60 25 ]);
            t_data_table = uitable (f, "Position", [ 0 15 1000 290 ], ...
                "Data", default_data, ...
                "ColumnFormat", columnformat_values);

            set (t_format_table, ...
                 "CellEditCallback", ...
                 @(x, y) update_column_format (y.NewData, y.Indices, ...
                                                t_data_table, popup_options));
            set (t_point_table, "CellEditCallback", ...
                 @(x, y) validate_point_table (x, y, t_data_table));
            set (t_editable_table, "CellEditCallback", ...
                 @(x,y) set (t_data_table, ...
                              "ColumnEditable", get (t_editable_table, "Data")));
            set (b_add, ...
                 "Callback", @(x, y) update_data (b_add, t_point_table, ...
                                                   t_type_table, t_data_table));
            set (t_data_table, "CellSelectionCallback", ...
                 @(x, y) update_point_table (y.Indices, t_point_table));
          endfunction

          function validate_point_table (h, dat, t_data_table)
            if (! (dat.NewData > 0 && ...
              dat.NewData < size (get (t_data_table, "Data"), dat.Indices(1, 1)) + 1))

              d = get (h, "Data");
              d(dat.Indices) = 1;
              set (h, "Data", d);
            endif
          endfunction

          function update_column_format (format, indices, t_data_table, ...
                                         popup_options)
            cf = get (t_data_table, "ColumnFormat");
            if (strcmp (format, "[]"))
              format = "";
            elseif (strcmp (format, "pop-up"))
              format = popup_options;
            endif
            cf{indices(1,2)} = format;
            set (t_data_table, "ColumnFormat", cf);
          endfunction

          function update_point_table (indices, t_point_table)
            if (isempty (indices))
              indices = [1, 1];
            endif
            set (t_point_table, "Data", indices(1,:));
          endfunction

          function update_data (b_add, t_point_table, t_type_table, ...
                                t_data_table)
            indices = get (b_add, "UserData");
            if (isempty (indices))
              indices = [1, 1];
            endif
            d = get (t_data_table, "Data");
            t_type_table_data = get (t_type_table, "Data");
            p = get (t_point_table, "Data");
            d(p(1,2), p(1,1)) = t_type_table_data(indices(1,2));
            set (t_data_table, "Data", d);
          endfunction

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

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

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

     The full list of properties is 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.

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

     The full list of properties is 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.

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

     The full list of properties is 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.

     The full list of properties is 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.


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.

 -- : movegui
 -- : movegui (H)
 -- : movegui (POS)
 -- : movegui (H, POS)
 -- : movegui (H, EVENT)
 -- : movegui (H, EVENT, POS)
     Move a figure specified by figure handle H to a position on the
     screen defined by POS.

     H is a figure handle, or a handle to a graphics object.  In the
     latter case, its parent figure will be used.  If unspecified, H
     will be set to the handle of the relevant figure if a callback is
     being executed (‘gcbf’), otherwise it will be set to the handle of
     the current figure (‘gcf’).

     POS is either a two-value numeric vector or a string.  If POS is
     numeric then it must be of the form ‘[h, v]’ specifying the
     horizontal and vertical offsets of the figure with respect to the
     screen.  A positive value indicates the offset between the left (or
     bottom for the vertical component) of the screen, and the left (or
     bottom) of the figure.  A negative value indicates the offset
     between the right (or top) of the screen and the right (or top) of
     the figure.

     Possible values for POS as a string are

     ‘north’
          Top center of the screen.

     ‘south’
          Bottom center of the screen.

     ‘east’
          Right center of the screen.

     ‘west’
          Left center of the screen.

     ‘northeast’
          Top right of the screen.

     ‘northwest’
          Top left of the screen.

     ‘southeast’
          Bottom right of the screen.

     ‘southwest’
          Bottom left of the screen.

     ‘center’
          Center of the screen.

     ‘onscreen (default)’
          The figure will be minimally moved to be entirely visible on
          the screen, with a 30 pixel extra padding from the sides of
          the screen.  This is the default value if none is provided.

     EVENT contains event data that will be ignored.  This construct
     facilitates a call to movegui from a callback.

 -- : 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
     or if H is the root graphics handle and no property PROP was
     provided, 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,  Next: Octave Workspace Windows,  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: Octave Workspace Windows,  Prev: User-Defined Preferences,  Up: GUI Development

35.6 Octave Workspace Windows
=============================

The functions below make windows that are a part of Octave’s own GUI
interface visible, and move the keyboard focus to the selected window.
Their utility lies in the ability to call these functions from a script
and highlight a window without using a mouse for selection.

 -- : commandhistory ()
     Show the GUI command history window and give it the keyboard focus.

     See also: *note commandwindow: XREFcommandwindow, *note
     filebrowser: XREFfilebrowser, *note workspace: XREFworkspace.

 -- : commandwindow ()
     Show the GUI command window and give it the keyboard focus.

     See also: *note commandhistory: XREFcommandhistory, *note
     filebrowser: XREFfilebrowser, *note workspace: XREFworkspace.

 -- : filebrowser ()
     Show the GUI file browser window and give it the keyboard focus.

     See also: *note commandwindow: XREFcommandwindow, *note
     commandhistory: XREFcommandhistory, *note workspace: XREFworkspace.

 -- : workspace ()
     Show the GUI workspace window and give it the keyboard focus.

     See also: *note commandwindow: XREFcommandwindow, *note
     commandhistory: XREFcommandhistory, *note filebrowser:
     XREFfilebrowser.


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 UTC (Coordinated Universal
     Time) 1 Jan 1970.  For example, on Monday February 17, 1997 at
     07:15:06 UTC, 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 UTC (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)
 -- : OLD_STATE = pause ("on")
 -- : OLD_STATE = pause ("off")
 -- : OLD_STATE = pause ("query")
     Suspend the execution of the program or change the state of the
     pause function.

     If invoked without an input arguments then the program is suspended
     until a character is typed.  If argument N is a positive real
     value, it indicates the number of seconds the program shall be
     suspended, 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;

     If invoked with a string argument "on", "off", or "query", the
     state of the pause function is changed or queried.  When the state
     is "off", the pause function returns immediately.  The optional
     return value contains the previous state of the pause function.  In
     the following example pause is disabled locally:

          old_state = pause ("off");
          tic; pause (0.05); toc
               ⊣ Elapsed time is 3.00407e-05 seconds.
          pause (old_state);

     While the program is suspended Octave still handles figures
     painting and graphics callbacks execution.

     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:* datenums represent a specific time for the Earth as a a
     whole.  They do not take in to account time zones (shifts in time
     based on location), nor seasonal changes due to Daylight Savings
     Time (shifts in time based on local regulation).  Be aware that it
     is possible to create datenums that, when interpreted by a function
     which accounts for time zone and DST shifts such as ‘datestr’, are
     nonexistent or ambiguous.

     *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’), a date vector (see
     ‘datevec’), or a string or cell array of strings.  In the latter
     case, it is passed to ‘datevec’ to guess the input date format.

     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 DIRNAME 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, *note isfile: XREFisfile, *note isfolder: XREFisfolder.

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

 -- : TF = isfile (F)
     Return true if F is a regular file and false otherwise.

     If F is a cell array of strings, TF is a logical array of the same
     size.

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

 -- : isdir (F)

     This function is not recommended.  Use ‘isfolder’ or
     ‘file_in_loadpath’ instead.

     Return true if F is a directory and false otherwise.

     Compatibility Note: The MATLAB function of the same name will also
     search for F in the load path directories.  To emulate this
     behavior use

          TF = ! isempty (file_in_loadpath (F))

     See also: *note isfolder: XREFisfolder, *note file_in_loadpath:
     XREFfile_in_loadpath, *note exist: XREFexist, *note stat: XREFstat,
     *note is_absolute_filename: XREFis_absolute_filename, *note
     is_rooted_relative_filename: XREFis_rooted_relative_filename.

 -- : isfolder (F)
 -- : TF = isfolder (F)
     Return true if F is a directory and false otherwise.

     If F is a cell array of strings, TF is a logical array of the same
     size.

     See also: *note isfile: XREFisfile, *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"})
            ⇒
                {
                  [1,1] = /home/username/data/f1.csv
                  [1,2] = /home/username/data/f2.csv
                  [1,3] = /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.  No
     tilde expansion of FNAME is performed.

     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, *note
     is_same_file: XREFis_same_file, *note tilde_expand:
     XREFtilde_expand.

 -- : 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.  No tilde expansion of
     FILE is performed.

     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
     isfolder: XREFisfolder, *note tilde_expand: XREFtilde_expand.

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

 -- : SAME = is_same_file (FILEPATH1, FILEPATH2)
     Return true if FILEPATH1 and FILEPATH2 refer to the same file.

     If either FILEPATH1 or FILEPATH2 is a cell array of strings, then
     an array of the same size is returned, containing the values
     described above for every member of the cell array.  The other
     argument may also be a cell array of strings (of the same size) or
     a string.

     Programming Notes: Depending on the operating system and file
     system, the same file or folder can be referred to with different
     paths.  In particular, paths on the Windows platform may differ in
     case (‘file1’ vs. ‘FILE1’), file separator (‘\’ vs. ‘/’), and
     format (‘A~spaces.txt’ (8.3 convention) vs. ‘A filename with
     spaces.txt’).  This function returns true if the paths in FILEPATH1
     and FILEPATH2 actually refer to the same file or folder, and false
     otherwise.

     Note that unlike ‘strcmp’, this function requires that FILEPATH1
     and FILEPATH2 exist, as well as point to the same location, in
     order to return true.

     See also: *note canonicalize_file_name: XREFcanonicalize_file_name,
     *note strcmp: XREFstrcmp.

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

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

 -- : bunzip2 (BZFILE)
 -- : bunzip2 (BZFILE, DIR)
 -- : FILELIST = bunzip2 (...)
     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.

 -- : gunzip (GZFILE)
 -- : gunzip (GZFILE, DIR)
 -- : FILELIST = gunzip (...)
     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)
 -- : FILELIST = untar (...)
     Unpack the TAR archive TARFILE.

     If DIR is specified the files are unpacked in this directory rather
     than the current directory.

     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.

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

     If DIR is specified the files are unpacked in this directory rather
     than the current directory.

     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::
* WWW Access::
* Base64 and Binary Data Transmission::

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


File: octave.info,  Node: FTP Objects,  Next: WWW Access,  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: WWW Access,  Next: Base64 and Binary Data Transmission,  Prev: FTP Objects,  Up: Networking Utilities

36.4.2 WWW Access
-----------------

Octave can communicate with websites across the Internet.  The ‘web’
function will launch an external web browser to interactively view a
site.  The remaining functions—‘urlread’, ‘urlwrite’, ‘webread’,
‘webwrite’—are internal Octave functions which can import or export data
to/from Octave and a website identified by a URL (Uniform Resource
Locator).

 -- : STATUS = web ()
 -- : STATUS = web (URL)
 -- : STATUS = web (URL, OPTION)
 -- : STATUS = web (URL, OPTION_1, ..., OPTION_N)
 -- : [STATUS, H, URL] = web (...)

     Open URL in the default system web browser.

     With no arguments given, the address <https://www.octave.org> is
     opened.

     Additional options can be passed for MATLAB compatibility, but are
     ignored.

        • ‘-browser’ Open URL in the default system browser.

        • ‘-new’ No effect on the system browser.

        • ‘-noaddressbox’ No effect on the system browser.

        • ‘-notoolbar’ No effect on the system browser.

     The return value STATUS has one of the values:

        • ‘0’ Found and opened system browser successfully.

        • ‘1’ Cannot find the system browser.

        • ‘2’ System browser found, but an error occurred.

     The return values HANDLE and URL are currently unimplemented but
     given for compatibility.

     See also: *note weboptions: XREFweboptions, *note webread:
     XREFwebread, *note webwrite: XREFwebwrite, *note urlread:
     XREFurlread, *note urlwrite: XREFurlwrite.

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

 -- : RESPONSE = webread (URL)
 -- : RESPONSE = webread (URL, NAME1, VALUE1, ...)
 -- : RESPONSE = webread (..., OPTIONS)

     Read content from RESTful web service.

     Read content from the web service specified by URL and return the
     content in RESPONSE.

     All key-value pairs given (NAME1, VALUE1, ...) are appended as
     query parameters to URL.  To place a query in the body of the
     message, use ‘webwrite’.  The web service defines the acceptable
     query parameters.

     OPTIONS is a ‘weboptions’ object that may be used to add other HTTP
     request options.  This argument can be used with either calling
     form.  See ‘help weboptions’ for a complete list of supported HTTP
     options.

     See also: *note weboptions: XREFweboptions, *note webwrite:
     XREFwebwrite.

 -- : RESPONSE = webwrite (URL, NAME1, VALUE1, ...)
 -- : RESPONSE = webwrite (URL, DATA)
 -- : RESPONSE = webwrite (..., OPTIONS)

     Write data to RESTful web services.

     Write content to the web service specified by URL and return the
     response in RESPONSE.

     All key-value pairs given (NAME1, VALUE1, ...) are added as pairs
     of query parameters to the body of request method (‘get’, ‘post’,
     ‘put’, etc.).

     OPTIONS is a ‘weboptions’ object that may be used to add other HTTP
     request options.  This argument can be used with either calling
     form.  See ‘help weboptions’ for a complete list of supported HTTP
     options.

     See also: *note weboptions: XREFweboptions, *note webread:
     XREFwebread.

 -- : OUTPUT = weboptions ()
 -- : OUTPUT = weboptions (NAME1, VALUE1, ...)

     Specify parameters for RESTful web services.

     ‘weboptions’ with no inputs returns a default ‘weboptions’ object
     to specify parameters for a request to a web service.  A
     ‘weboptions’ object can be an optional input argument to the
     ‘webread’ and ‘webwrite’ functions.

     Multiple name and value pair arguments may be specified in any
     order as NAME1, VALUE1, NAME2, VALUE2, etc.

     The option names must match *exactly* one of those specified in the
     table below.

     The following options are available:

        • ‘CharacterEncoding’ — Specify the character encoding of the
          data:

          ‘auto’ (default), ‘UTF-8’, ‘US-ASCII’ ‘auto’ chooses an
          encoding based on the content-type of the data.

        • ‘UserAgent’ — Specify the User Agent for the connection.

          Default value is ‘GNU Octave/version’, where ‘version’ is the
          current version of Octave as returned by ‘version’.

        • ‘Timeout’ — Specify the timeout value for the connection in
          seconds.

          Default is 10 seconds.  ‘Inf’ is not currently supported.

        • ‘Username’ — User identifier for a basic HTTP connection.

          Default is NULL.  It must be a string.

        • ‘Password’ — User authentication password for HTTP connection.

          Default is NULL.  It must be a string or character vector.
          Programming Note: If you display a ‘weboption’ object with the
          Password property set, the value is displayed as a string
          containing ’*’.  However, the object stores the value of the
          Password property as plain text.

        • ‘KeyName’ — Specify the name of an additional key to be added
          to the HTTP request header.  It should be coupled with
          ‘KeyValue’.  It must be a string or character vector.

        • ‘KeyValue’ — Specify the value of the key ‘KeyName’.

          ‘KeyName’ must be present in order to assign to this field.

        • ‘HeaderFields’ — Specify the header fields for the connection.

          Names and values of header fields, specified as an m-by-2
          array of strings or cell array of character vectors to add to
          the HTTP request header.  HeaderFields{i,1} is the name of a
          field and HeaderFields{i,2} is its value.

               weboptions ("HeaderFields", {"Content-Length" "78";"Content-Type" "application/json"})
               Creates a weboptions object that contains two header fields: Content-Length
               with value 78 and Content-Type with value application/json.

        • ‘ContentType’ — Specify the content type of the data.

          The following values are available: ‘auto’, ‘text’, ‘json’

          Default is ‘auto’.  It automatically determines the content
          type.  All other formats like ‘audio’, ‘binary’, etc.
          available in MATLAB are not currently supported.

        • ‘ContentReader’ — Not yet implemented.  Only for MATLAB
          compatibility.

        • ‘MediaType’ — Not yet implemented.  Only for MATLAB
          compatibility.

        • ‘RequestMethod’ — Specifies the type of request to be made.

          The following methods are available: ‘get’, ‘put’, ‘post’,
          ‘delete’, ‘patch’

          ‘webread’ uses the HTTP GET method.  ‘webwrite’ uses the HTTP
          POST method as default.

        • ‘ArrayFormat’ – Not yet implemented.  Only for MATLAB
          compatibility.

        • ‘CertificateFilename’ — Not yet implemented.  Only for MATLAB
          compatibility.

     See also: *note webread: XREFwebread, *note webwrite: XREFwebwrite.


File: octave.info,  Node: Base64 and Binary Data Transmission,  Prev: WWW Access,  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 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"));

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

     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.

     By default, recognized file types are

     ‘.m’
          Open file in the editor.  No OUTPUT value is returned.

     ‘.mat’
     ‘octave-workspace’
          Open the data file with ‘load’.  If no return value OUTPUT is
          requested, variables are loaded in the base workspace.
          Otherwise OUTPUT will be a structure containing loaded data.
          *Note load function: XREFload.

     ‘.ofig’
          Open the figure with ‘hgload’.  *Note hgload function:
          XREFhgload.

     ‘.fig, .ofig’
          Load the figure

     ‘.exe’
          Execute the program (on Windows systems only).  No OUTPUT
          value is returned.

     Custom file extensions may also be handled if a function ‘openxxx’,
     where ‘xxx’ is the extension, is found in the load path.  The
     function must accept the file name as input.  For example, in order
     to load ".dat" data files in the base workspace, as is done by
     default for ".mat" files, one may define "opendat.m" with the
     following contents:

          function retval = opendat (fname)
            evalin ("base", sprintf ("load ('%s');", fname));
          endfunction

     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
 -- : OLD_DIR = cd (DIR)
 -- : chdir ...
     Change the current working directory to DIR.

     If called with no input or output arguments, 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 ()
             ⊣ x86_64-pc-linux-gnu

          mycomp = computer ()
             ⇒ mycomp = x86_64-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_EXEC_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 information returned for the "-blas" and "-lapack" options
     might be unreliable.  It might report which library was linked in
     when Octave was built instead of which library is currently used.

     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 query a specific
     component.

     When called with an output argument, return a vector of structures
     describing Octave and each installed package.  Each structure
     includes the following fields.

     ‘Name’
          Package name.

     ‘Version’
          Version of the package.

     ‘Release’
          Release of the package (currently unused, defaults to ‘[]’).

     ‘Date’
          Date that the version was released.

     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

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

 -- : verLessThan (PACKAGE, VERSION)
     Return true if the installed version of the package is less than
     VERSION.

     PACKAGE is the name of the package to check.  Use "Octave" as the
     PACKAGE to check the version of Octave itself.

     VERSION is the version to compare it to.  A version is a string in
     the format accepted by ‘compare_versions’: an arbitrarily long
     string composed 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").

     Examples:

          tf = verLessThan ("Octave", "5")
          ⇒ tf = 0

          tf = verLessThan ("io", "2.4.12")
          ⇒ ...

          if (! verLessThan ("Octave", "5"))
            ## ... use new Octave 5 features ...
          endif

     See also: *note compare_versions: XREFcompare_versions, *note
     version: XREFversion, *note ver: XREFver, *note pkg: XREFpkg.

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

     Packages can be installed globally (i.e., for all users of the
     system) or locally (i.e., for the current user only).

     Global packages are installed by default in a system-wide location.
     This is usually a subdirectory of the folder where Octave itself is
     installed.  Therefore, Octave needs write access to this folder to
     install global packages.  That usually means that Octave has to run
     with root access (or "Run as administrator" on Windows) to be able
     to install packages globally.

     In contrast, local packages are installed by default in the user’s
     home directory (profile on Windows) and are only available to that
     specific user.  Usually, they can be installed without root access
     (or administrative privileges).

     For global and local packages, there are separate databases holding
     the information about the installed packages.  If some package is
     installed globally as well as locally, the local installation takes
     precedence over ("shadows") the global one.  Which package
     installation (global or local) is used can also be manipulated by
     using prefixes and/or using the ‘local_list’ input argument.  Using
     these mechanisms, several different releases of one and the same
     package can be installed side by side as well (but cannot be loaded
     simultaneously).

     Packages might depend on external software and/or other packages.
     To be able to install such packages, these dependencies should be
     installed beforehand.  A package that depends on other package(s)
     can still be installed using the ‘-nodeps’ flag.  The effects of
     unsatisfied dependencies on external software—like
     libraries—depends on the individual package.

     Packages must be loaded before they can be used.  When loading a
     package, Octave performs the following tasks:
       1. If the package depends on other packages (and ‘pkg load’ is
          called without the ‘-nodeps’ option), the package is not
          loaded immediately.  Instead, those dependencies are loaded
          first (recursively if needed).

       2. When all dependencies are satisfied, the package’s
          subdirectories are added to the search path.

     This load order leads to functions that are provided by
     dependencies being potentially shadowed by functions of the same
     name that are provided by top-level packages.

     Each time, a package is added to the search path, initialization
     script(s) for the package are automatically executed if they are
     provided by the package.

     Depending on the value of COMMAND and on the number of requested
     return arguments, ‘pkg’ can be used to perform several tasks.
     Possible values for COMMAND are:

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

          To update a single package use ‘pkg install -forge’

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

          Note: When loading a package, ‘pkg’ will automatically try to
          load any unloaded dependencies as well, unless the ‘-nodeps’
          flag has been specified.  For example,

               pkg load signal

          adds the ‘signal’ package and also tries to load its
          dependency: the ‘control’ package.  Be aware that the
          functionality of package(s) loaded will probably be impacted
          by use of the ‘-nodeps’ flag.  Even if necessary dependencies
          are loaded later, the functionality of top-level packages can
          still be affected because the optimal loading order may not
          have been followed.

     ‘unload’
          Remove named packages from the path.  After unloading a
          package it is no longer possible to use the functions provided
          by the package.  Trying to unload a package that other loaded
          packages still depend on will result in an error; no packages
          will be unloaded in this case.  A package can be forcibly
          removed with the ‘-nodeps’ flag, but be aware that the
          functionality of dependent packages will likely be affected.
          As when loading packages, reloading dependencies after having
          unloaded them with the ‘-nodeps’ flag may not restore all
          functionality of the dependent packages as the required
          loading order may be incorrect.

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

               ## describe control and signal packages
               pkg describe control signal

          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.

     ‘test’
          Perform the built-in self tests contained in all functions
          provided by the named packages.  For example:

               pkg test image

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


File: octave.info,  Node: The DESCRIPTION File,  Next: The INDEX File,  Up: Creating Packages

37.4.1 The DESCRIPTION File
---------------------------

The ‘DESCRIPTION’ file contains various information about the package,
such as its name, author, and version.  This file has a very simple
format

   • Lines starting with ‘#’ are comments.

   • Lines starting with a blank character are continuations from the
     previous line.

   • Everything else is of the form ‘NameOfOption: ValueOfOption’.

The following is a simple example of a ‘DESCRIPTION’ file

     Name: The name of my package
     Version: 1.0.0
     Date: 2007-18-04
     Author: The name (and possibly email) of the package author.
     Maintainer: The name (and possibly email) of the current
      package maintainer.
     Title: The title of the package
     Description: A short description of the package.  If this
      description gets too long for one line it can continue
      on the next by adding a space to the beginning of the
      following lines.
     License: GPLv3+

   The package manager currently recognizes the following keywords

‘Name’
     Name of the package.

‘Version’
     Version of the package.  A package version is typically digits
     separated by dots but may also contain ‘+’, ‘-’, ‘~’, and
     alphanumeric characters (in the "C" locale).  For example, "2.1.0+"
     could indicate a development version of a package.  Versions are
     compared using *note compare_versions: XREFcompare_versions.

‘Date’
     Date of last update.

‘Author’
     Original author of the package.

‘Maintainer’
     Maintainer of the package.

‘Title’
     A one line description of the package.

‘Description’
     A one paragraph description of the package.

‘Categories’
     Optional keyword describing the package (if no ‘INDEX’ file is
     given this is mandatory).

‘Problems’
     Optional list of known problems.

‘Url’
     Optional list of homepages related to the package.

‘Depends’
     A list of other Octave packages that this package depends on.  This
     can include dependencies on particular versions, with the following
     format:

          Depends: package (>= 1.0.0)

     Possible operators are ‘<’, ‘<=’, ‘==’, ‘>=’ or ‘>’.  If the part
     of the dependency in ‘()’ is missing, any version of the package is
     acceptable.  Multiple dependencies can be defined as a comma
     separated list.  This can be used to define a range of versions of
     a particular package:

          Depends: package (>= 1.0.0), package (< 1.5.0)

     It is also possible to depend on particular versions of Octave
     core:

          Depends: octave (>= 3.8.0)

‘License’
     An optional short description of the used license (e.g., GPL
     version 3 or newer).  This is optional since the file ‘COPYING’ is
     mandatory.

‘SystemRequirements’
     These are the external install dependencies of the package and are
     not checked by the package manager.  This is here as a hint to the
     distribution packager.  They follow the same conventions as the
     ‘Depends’ keyword.

‘BuildRequires’
     These are the external build dependencies of the package and are
     not checked by the package manager.  This is here as a hint to the
     distribution packager.  They follow the same conventions as the
     ‘Depends’ keyword.  Note that in general, packaging systems such as
     ‘rpm’ or ‘deb’ autoprobe the install dependencies from the build
     dependencies, and therefore a ‘BuildRequires’ dependency usually
     removes the need for a ‘SystemRequirements’ dependency.

The developer is free to add additional arguments to the ‘DESCRIPTION’
file for their own purposes.  One further detail to aid the packager is
that the ‘SystemRequirements’ and ‘BuildRequires’ keywords can have a
distribution dependent section, and the automatic build process will use
these.  An example of the format of this is

     BuildRequires: libtermcap-devel [Mandriva] libtermcap2-devel

where the first package name will be used as a default and if the RPMs
are built on a Mandriva distribution, then the second package name will
be used instead.


File: octave.info,  Node: The INDEX File,  Next: PKG_ADD and PKG_DEL Directives,  Prev: The DESCRIPTION File,  Up: Creating Packages

37.4.2 The INDEX File
---------------------

The optional ‘INDEX’ file provides a categorical view of the functions
in the package.  This file has a very simple format

   • Lines beginning with ‘#’ are comments.

   • The first non-comment line should look like this

          toolbox >> Toolbox name

   • Lines beginning with an alphabetical character indicates a new
     category of functions.

   • Lines starting with a white space character indicate that the
     function names on the line belong to the last mentioned category.

The format can be summarized with the following example:

     # A comment
     toolbox >> Toolbox name
     Category Name 1
      function1 function2 function3
      function4
     Category Name 2
      function2 function5

   If you wish to refer to a function that users might expect to find in
your package but is not there, providing a work around or pointing out
that the function is available elsewhere, you can use:

     fn = workaround description

This workaround description will not appear when listing functions in
the package with ‘pkg describe’ but they will be published in the HTML
documentation online.  Workaround descriptions can use any HTML markup,
but keep in mind that it will be enclosed in a bold-italic environment.
For the special case of:

     fn = use <code>alternate expression</code>

the bold-italic is automatically suppressed.  You will need to use
‘<code>’ even in references:

     fn = use <a href="someothersite.html"><code>fn</code></a>

Sometimes functions are only partially compatible, in which case you can
list the non-compatible cases separately.  To refer to another function
in the package, use ‘<f>fn</f>’.  For example:

     eig (a, b) = use <f>qz</f>

Since sites may have many missing functions, you can define a macro
rather than typing the same link over and again.

     $id = expansion

defines the macro id.  You can use ‘$id’ anywhere in the description and
it will be expanded.  For example:

     $TSA = see <a href="link_to_spctools">SPC Tools</a>
     arcov = $TSA <code>armcv</code>

id is any string of letters, numbers and ‘_’.


File: octave.info,  Node: PKG_ADD and PKG_DEL Directives,  Next: Missing Components,  Prev: The INDEX File,  Up: Creating Packages

37.4.3 PKG_ADD and PKG_DEL Directives
-------------------------------------

If the package contains files called ‘PKG_ADD’ or ‘PKG_DEL’ the commands
in these files will be executed when the package is added or removed
from the users path.  In some situations such files are a bit cumbersome
to maintain, so the package manager supports automatic creation of such
files.  If a source file in the package contains a ‘PKG_ADD’ or
‘PKG_DEL’ directive they will be added to either the ‘PKG_ADD’ or
‘PKG_DEL’ files.

   In ‘m’-files a ‘PKG_ADD’ directive looks like this

     ## PKG_ADD: some_octave_command

Such lines should be added before the ‘function’ keyword.  In C++ files
a ‘PKG_ADD’ directive looks like this

     // PKG_ADD: some_octave_command

In both cases ‘some_octave_command’ should be replaced by the command
that should be placed in the ‘PKG_ADD’ file. ‘PKG_DEL’ directives work
in the same way, except the ‘PKG_ADD’ keyword is replaced with ‘PKG_DEL’
and the commands get added to the ‘PKG_DEL’ file.


File: octave.info,  Node: Missing Components,  Prev: PKG_ADD and PKG_DEL Directives,  Up: Creating Packages

37.4.4 Missing Components
-------------------------

If a package relies on a component, such as another Octave package, that
may not be present it may be useful to install a function which informs
users what to do when a particular component is missing.  The function
must be written by the package maintainer and registered with Octave
using ‘missing_component_hook’.

 -- : VAL = missing_component_hook ()
 -- : OLD_VAL = missing_component_hook (NEW_VAL)
 -- : missing_component_hook (NEW_VAL, "local")
     Query or set the internal variable that specifies the function to
     call when a component of Octave is missing.

     This can be useful for packagers that may split the Octave
     installation into multiple sub-packages, for example, to provide a
     hint to users for how to install the missing components.

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines it
     calls.  The original variable value is restored when exiting the
     function.

     The hook function is expected to be of the form

          FCN (COMPONENT)

     Octave will call FCN with the name of the function that requires
     the component and a string describing the missing component.  The
     hook function should return an error message to be displayed.

     See also: *note missing_function_hook: XREFmissing_function_hook.


File: octave.info,  Node: External Code Interface,  Next: Test and Demo Functions,  Prev: Packages,  Up: Top

Appendix A External Code Interface
**********************************

"The sum of human wisdom is not contained in any one language"

   — Ezra Pound

   Octave is a fantastic language for solving many problems in science
and engineering.  However, it is not the only computer language and
there are times when you may want to use code written in other
languages.  Good reasons for doing so include: 1) not re-inventing the
wheel; existing function libraries which have been thoroughly tested and
debugged or large scale simulation codebases are a good example, 2)
accessing unique capabilities of a different language; for example the
well-known regular expression functions of Perl (but don’t do that
because ‘regexp’ already exists in Octave).

   Performance should generally *not* be a reason for using compiled
extensions.  Although compiled extensions can run faster, particularly
if they replace a loop in Octave code, this is almost never the best
path to take.  First, there are many techniques to speed up Octave
performance while remaining within the language.  Second, Octave is a
high-level language that makes it easy to perform common mathematical
tasks.  Giving that up means shifting the focus from solving the real
problem to solving a computer programming problem.  It means returning
to low-level constructs such as pointers, memory management,
mathematical overflow/underflow, etc.  Because of the low level nature,
and the fact that the compiled code is executed outside of Octave, there
is the very real possibility of crashing the interpreter and losing
work.

   Before going further, you should first determine if you really need
to bother writing code outside of Octave.

   • Can I get the same functionality using the Octave scripting
     language alone?

     Even when a function already exists outside the language, it may be
     better to simply reproduce the behavior in an m-file rather than
     attempt to interface to the outside code.

   • Is the code thoroughly optimized for Octave?

     If performance is an issue you should always start with the
     in-language techniques for getting better performance.  Chief among
     these is vectorization (*note Vectorization and Faster Code
     Execution::) which not only makes the code concise and more
     understandable but improves performance (10X-100X). If loops must
     be used, make sure that the allocation of space for variables takes
     place outside the loops using an assignment to a matrix of the
     right size, or zeros.

   • Does the code make as much use as possible of existing built-in
     library routines?

     These routines are highly optimized and many do not carry the
     overhead of being interpreted.

   • Does writing a dynamically linked function represent a useful
     investment of your time, relative to staying in Octave?

     It will take time to learn Octave’s interface for external code and
     there will inevitably be issues with tools such as compilers.

   With that said, Octave offers a versatile interface for including
chunks of compiled code as dynamically linked extensions.  These
dynamically linked functions can be called from the interpreter in the
same manner as any ordinary function.  The interface is bi-directional
and external code can call Octave functions (like ‘plot’) which
otherwise might be very difficult to develop.

   The interface is centered around supporting the languages C++, C, and
Fortran.  Octave itself is written in C++ and can call external C++/C
code through its native oct-file interface.  The C language is also
supported through the mex-file interface for compatibility with MATLAB.
Fortran code is easiest to reach through the oct-file interface.

   Because many other languages provide C or C++ APIs it is relatively
simple to build bridges between Octave and other languages.  This is
also a way to bridge to hardware resources which often have device
drivers written in C.

* Menu:

* Oct-Files::
* Mex-Files::
* Standalone Programs::
* Java Interface::


File: octave.info,  Node: Oct-Files,  Next: Mex-Files,  Up: External Code Interface

A.1 Oct-Files
=============

* Menu:

* Getting Started with Oct-Files::
* Matrices and Arrays in Oct-Files::
* Character Strings in Oct-Files::
* Cell Arrays in Oct-Files::
* Structures in Oct-Files::
* Sparse Matrices in Oct-Files::
* Accessing Global Variables in Oct-Files::
* Calling Octave Functions from Oct-Files::
* Calling External Code from Oct-Files::
* Allocating Local Memory in Oct-Files::
* Input Parameter Checking in Oct-Files::
* Exception and Error Handling in Oct-Files::
* Documentation and Testing of Oct-Files::


File: octave.info,  Node: Getting Started with Oct-Files,  Next: Matrices and Arrays in Oct-Files,  Up: Oct-Files

A.1.1 Getting Started with Oct-Files
------------------------------------

Oct-files are pieces of C++ code that have been compiled with the Octave
API into a dynamically loadable object.  They take their name from the
file which contains the object which has the extension ‘.oct’.

   Finding a C++ compiler, using the correct switches, adding the right
include paths for header files, etc. is a difficult task.  Octave
automates this by providing the ‘mkoctfile’ command with which to build
oct-files.  The command is available from within Octave or at the shell
command line.

 -- : mkoctfile [-options] file ...
 -- : [OUTPUT, STATUS] = mkoctfile (...)

     The ‘mkoctfile’ function compiles source code written in C, C++, or
     Fortran.  Depending on the options used with ‘mkoctfile’, the
     compiled code can be called within Octave or can be used as a
     stand-alone application.

     ‘mkoctfile’ can be called from the shell prompt or from the Octave
     prompt.  Calling it from the Octave prompt simply delegates the
     call to the shell prompt.  Any output is stored in the OUTPUT
     variable and the exit status in the STATUS variable.  If called
     with no outputs and the compilation fails then Octave will emit an
     error.  If the programmer requests OUTPUT or STATUS, however,
     Octave will merely issue a warning and it is the programmer’s
     responsibility to verify the command was successful.

     ‘mkoctfile’ accepts the following options, all of which are
     optional except for the filename of the code you wish to compile:

     ‘-I DIR’
          Add the include directory DIR to compile commands.

     ‘-D DEF’
          Add the definition DEF to the compiler call.

     ‘-l LIB’
          Add the library LIB to the link command.

     ‘-L DIR’
          Add the library directory DIR to the link command.

     ‘-M’
     ‘--depend’
          Generate dependency files (.d) for C and C++ source files.

     ‘-R DIR’
          Add the run-time path to the link command.

     ‘-Wl,...’
          Pass options to the linker like "-Wl,-rpath=...".  The quotes
          are needed since commas are interpreted as command separators.

     ‘-W...’
          Pass options to the assembler like "-Wa,OPTION".

     ‘-c’
          Compile but do not link.

     ‘-g’
          Enable debugging options for compilers.

     ‘-o FILE’
     ‘--output FILE’
          Output filename.  Default extension is ‘.oct’ (or ‘.mex’ if
          ‘--mex’ is specified) unless linking a stand-alone executable.

     ‘-p VAR’
     ‘--print VAR’
          Print configuration variable VAR.  There are three categories
          of variables:

          Octave configuration variables that users may override with
          environment variables.  These are used in commands that
          ‘mkoctfile’ executes.

                  ALL_CFLAGS                  INCLUDEDIR
                  ALL_CXXFLAGS                LAPACK_LIBS
                  ALL_FFLAGS                  LDFLAGS
                  ALL_LDFLAGS                 LD_STATIC_FLAG
                  BLAS_LIBS                   LFLAGS
                  CC                          LIBDIR
                  CFLAGS                      LIBOCTAVE
                  CPICFLAG                    LIBOCTINTERP
                  CPPFLAGS                    OCTAVE_LINK_OPTS
                  CXX                         OCTINCLUDEDIR
                  CXXFLAGS                    OCTAVE_LIBS
                  CXXLD                       OCTAVE_LINK_DEPS
                  CXXPICFLAG                  OCTLIBDIR
                  DL_LDFLAGS                  OCT_LINK_DEPS
                  F77                         OCT_LINK_OPTS
                  F77_INTEGER8_FLAG           RDYNAMIC_FLAG
                  FFLAGS                      SPECIAL_MATH_LIB
                  FPICFLAG                    XTRA_CFLAGS
                  INCFLAGS                    XTRA_CXXFLAGS

          Octave configuration variables as above, but currently unused
          by ‘mkoctfile’.

                  AR
                  DEPEND_EXTRA_SED_PATTERN
                  DEPEND_FLAGS
                  FFTW3F_LDFLAGS
                  FFTW3F_LIBS
                  FFTW3_LDFLAGS
                  FFTW3_LIBS
                  FFTW_LIBS
                  FLIBS
                  LIBS
                  RANLIB
                  READLINE_LIBS

          Octave configuration variables that are provided for
          informational purposes only.  Except for ‘OCTAVE_HOME’ and
          ‘OCTAVE_EXEC_HOME’, users may not override these variables.

          If ‘OCTAVE_HOME’ or ‘OCTAVE_EXEC_HOME’ are set in the
          environment, then other variables are adjusted accordingly
          with ‘OCTAVE_HOME’ or ‘OCTAVE_EXEC_HOME’ substituted for the
          original value of the directory specified by the ‘--prefix’ or
          ‘--exec-prefix’ options that were used when Octave was
          configured.

                  API_VERSION                 LOCALFCNFILEDIR
                  ARCHLIBDIR                  LOCALOCTFILEDIR
                  BINDIR                      LOCALSTARTUPFILEDIR
                  CANONICAL_HOST_TYPE         LOCALVERARCHLIBDIR
                  DATADIR                     LOCALVERFCNFILEDIR
                  DATAROOTDIR                 LOCALVEROCTFILEDIR
                  DEFAULT_PAGER               MAN1DIR
                  EXEC_PREFIX                 MAN1EXT
                  EXEEXT                      MANDIR
                  FCNFILEDIR                  OCTAVE_EXEC_HOME
                  IMAGEDIR                    OCTAVE_HOME
                  INFODIR                     OCTAVE_VERSION
                  INFOFILE                    OCTDATADIR
                  LIBEXECDIR                  OCTDOCDIR
                  LOCALAPIARCHLIBDIR          OCTFILEDIR
                  LOCALAPIFCNFILEDIR          OCTFONTSDIR
                  LOCALAPIOCTFILEDIR          STARTUPFILEDIR
                  LOCALARCHLIBDIR

     ‘--link-stand-alone’
          Link a stand-alone executable file.

     ‘--mex’
          Assume creation of a MEX file.  Set the default output
          extension to ‘.mex’.

     ‘-s’
     ‘--strip’
          Strip the output file.

     ‘-v’
     ‘--verbose’
          Echo commands as they are executed.

     ‘file’
          The file to compile or link.  Recognized file types are:

                  .c    C source
                  .cc   C++ source
                  .cp   C++ source
                  .cpp  C++ source
                  .CPP  C++ source
                  .cxx  C++ source
                  .c++  C++ source
                  .C    C++ source
                  .f    Fortran source (fixed form)
                  .F    Fortran source (fixed form)
                  .f90  Fortran source (free form)
                  .F90  Fortran source (free form)
                  .o    object file
                  .a    library file

   Consider the following short example which introduces the basics of
writing a C++ function that can be linked to Octave.

     #include <octave/oct.h>
     
     DEFUN_DLD (helloworld, args, nargout,
                "Hello World Help String")
     {
       octave_stdout << "Hello World has "
                     << args.length () << " input arguments and "
                     << nargout << " output arguments.\n";
     
       // Return empty matrices for any outputs
       octave_value_list retval (nargout);
       for (int i = 0; i < nargout; i++)
         retval(i) = octave_value (Matrix ());
     
       return retval;
     }

   The first critical line is ‘#include <octave/oct.h>’ which makes
available most of the definitions necessary for a C++ oct-file.  Note
that ‘octave/oct.h’ is a C++ header and cannot be directly ‘#include’’ed
in a C source file, nor any other language.

   Included by ‘oct.h’ is a definition for the macro ‘DEFUN_DLD’ which
creates a dynamically loaded function.  This macro takes four arguments:

  1. The function name as it will be seen in Octave,

  2. The list of arguments to the function of type ‘octave_value_list’,

  3. The number of output arguments, which can be—and often is—omitted
     if not used, and

  4. The string to use for the help text of the function.

   The return type of functions defined with ‘DEFUN_DLD’ is always
‘octave_value_list’.

   There are a couple of important considerations in the choice of
function name.  First, it must be a valid Octave function name and so
must be a sequence of letters, digits, and underscores not starting with
a digit.  Second, as Octave uses the function name to define the
filename it attempts to find the function in, the function name in the
‘DEFUN_DLD’ macro must match the filename of the oct-file.  Therefore,
the above function should be in a file ‘helloworld.cc’, and would be
compiled to an oct-file using the command

     mkoctfile helloworld.cc

   This will create a file called ‘helloworld.oct’ that is the compiled
version of the function.  It should be noted that it is perfectly
acceptable to have more than one ‘DEFUN_DLD’ function in a source file.
However, there must either be a symbolic link to the oct-file for each
of the functions defined in the source code with the ‘DEFUN_DLD’ macro
or the ‘autoload’ (*note Function Files::) function should be used.

   The rest of the function shows how to find the number of input
arguments, how to print through the Octave pager, and how to return from
the function.  After compiling this function as above, an example of its
use is

     helloworld (1, 2, 3)
     ⊣ Hello World has 3 input arguments and 0 output arguments.

   Subsequent sections show how to use specific classes from Octave’s
core internals.  Base classes like ‘dMatrix’ (a matrix of double values)
are found in the directory ‘liboctave/array’.  The definitive reference
for how to use a particular class is the header file itself.  However,
it is often enough simply to study the examples in the manual in order
to be able to use a class.


File: octave.info,  Node: Matrices and Arrays in Oct-Files,  Next: Character Strings in Oct-Files,  Prev: Getting Started with Oct-Files,  Up: Oct-Files

A.1.2 Matrices and Arrays in Oct-Files
--------------------------------------

Octave supports a number of different array and matrix classes, the
majority of which are based on the ‘Array’ class.  The exception are the
sparse matrix types discussed separately below.  There are three basic
matrix types:

‘Matrix’
     A double precision matrix class defined in ‘dMatrix.h’

‘ComplexMatrix’
     A complex matrix class defined in ‘CMatrix.h’

‘BoolMatrix’
     A boolean matrix class defined in ‘boolMatrix.h’

   These are the basic two-dimensional matrix types of Octave.  In
addition there are a number of multi-dimensional array types including

‘NDArray’
     A double precision array class defined in ‘dNDArray.h’

‘ComplexNDarray’
     A complex array class defined in ‘CNDArray.h’

‘boolNDArray’
     A boolean array class defined in ‘boolNDArray.h’

‘int8NDArray’
‘int16NDArray’
‘int32NDArray’
‘int64NDArray’
     8, 16, 32, and 64-bit signed array classes defined in
     ‘int8NDArray.h’, ‘int16NDArray.h’, etc.

‘uint8NDArray’
‘uint16NDArray’
‘uint32NDArray’
‘uint64NDArray’
     8, 16, 32, and 64-bit unsigned array classes defined in
     ‘uint8NDArray.h’, ‘uint16NDArray.h’, etc.

   There are several basic ways of constructing matrices or
multi-dimensional arrays.  Using the class ‘Matrix’ as an example one
can

   • Create an empty matrix or array with the empty constructor.  For
     example:

          Matrix a;

     This can be used for all matrix and array types.

   • Define the dimensions of the matrix or array with a dim_vector
     which has the same characteristics as the vector returned from
     ‘size’.  For example:

          dim_vector dv (2, 3);  // 2 rows, 3 columns
          Matrix a (dv);

     This can be used for all matrix and array types.

   • Define the number of rows and columns in the matrix.  For example:

          Matrix a (2, 2)

     This constructor can *only* be used with matrix types.

   These types all share a number of basic methods and operators.  Many
bear a resemblance to functions that exist in the interpreter.  A
selection of useful methods include

 -- Method: T& operator () (octave_idx_type)
 -- Method: T& elem (octave_idx_type)
     The ‘()’ operator or ‘elem’ method allow the values of the matrix
     or array to be read or set.  These methods take a single argument,
     which is of type ‘octave_idx_type’, that is the index into the
     matrix or array.  Additionally, the matrix type allows two argument
     versions of the ‘()’ operator and ‘elem’ method, giving the row and
     column index of the value to get or set.

   Note that these functions do significant error checking and so in
some circumstances the user might prefer to access the data of the array
or matrix directly through the ‘fortran_vec’ method discussed below.

 -- Method: octave_idx_type numel (void) const
     The total number of elements in the matrix or array.

 -- Method: size_t byte_size (void) const
     The number of bytes used to store the matrix or array.

 -- Method: dim_vector dims (void) const
     The dimensions of the matrix or array in value of type
     ‘dim_vector’.

 -- Method: int ndims (void) const
     The number of dimensions of the matrix or array.  Matrices are
     always 2-D, but arrays can be N-dimensional.

 -- Method: void resize (const dim_vector&)
 -- Method: void resize (nrows, ncols)
     A method taking either an argument of type ‘dim_vector’, or, in the
     case of a matrix, two arguments of type ‘octave_idx_type’ defining
     the number of rows and columns in the matrix.

 -- Method: T* fortran_vec (void)
     This method returns a pointer to the underlying data of the matrix
     or array so that it can be manipulated directly, either within
     Octave or by an external library.

   Operators such as ‘+’, ‘-’, or ‘*’ can be used on the majority of the
matrix and array types.  In addition there are a number of methods that
are of interest only for matrices such as ‘transpose’, ‘hermitian’,
‘solve’, etc.

   The typical way to extract a matrix or array from the input arguments
of ‘DEFUN_DLD’ function is as follows

     #include <octave/oct.h>
     
     DEFUN_DLD (addtwomatrices, args, , "Add A to B")
     {
       if (args.length () != 2)
         print_usage ();
     
       NDArray A = args(0).array_value ();
       NDArray B = args(1).array_value ();
     
       return octave_value (A + B);
     }

   To avoid segmentation faults causing Octave to abort, this function
explicitly checks that there are sufficient arguments available before
accessing these arguments.  It then obtains two multi-dimensional arrays
of type ‘NDArray’ and adds these together.  Note that the ‘array_value’
method is called without using the ‘is_matrix_type’ method.  If an error
occurs when attempting to extract the value, Octave will print a message
and throw an exception.  The reason to prefer this coding structure is
that the arguments might be a type which is not an ‘NDArray’, but for
which it would make sense to convert them to one.  The ‘array_value’
method allows this conversion to be performed transparently when
possible.  If you need to catch errors like this, and perform some kind
of cleanup or other operation, you can catch the
‘octave_execution_error’ exception.

   ‘A + B’, operating on two ‘NDArray’ objects returns an ‘NDArray’,
which is cast to an ‘octave_value’ on the return from the function.  An
example of the use of this demonstration function is

     addtwomatrices (ones (2, 2), eye (2, 2))
           ⇒  2  1
               1  2

   A list of the basic ‘Matrix’ and ‘Array’ types, the methods to
extract these from an ‘octave_value’, and the associated header file is
listed below.

Type                   Function                      Source Code
----------------------------------------------------------------------------
‘RowVector’            ‘row_vector_value’            ‘dRowVector.h’
‘ComplexRowVector’     ‘complex_row_vector_value’    ‘CRowVector.h’
‘ColumnVector’         ‘column_vector_value’         ‘dColVector.h’
‘ComplexColumnVector’  ‘complex_column_vector_value’ ‘CColVector.h’
‘Matrix’               ‘matrix_value’                ‘dMatrix.h’
‘ComplexMatrix’        ‘complex_matrix_value’        ‘CMatrix.h’
‘boolMatrix’           ‘bool_matrix_value’           ‘boolMatrix.h’
‘charMatrix’           ‘char_matrix_value’           ‘chMatrix.h’
‘NDArray’              ‘array_value’                 ‘dNDArray.h’
‘ComplexNDArray’       ‘complex_array_value’         ‘CNDArray.h’
‘boolNDArray’          ‘bool_array_value’            ‘boolNDArray.h’
‘charNDArray’          ‘char_array_value’            ‘charNDArray.h’
‘int8NDArray’          ‘int8_array_value’            ‘int8NDArray.h’
‘int16NDArray’         ‘int16_array_value’           ‘int16NDArray.h’
‘int32NDArray’         ‘int32_array_value’           ‘int32NDArray.h’
‘int64NDArray’         ‘int64_array_value’           ‘int64NDArray.h’
‘uint8NDArray’         ‘uint8_array_value’           ‘uint8NDArray.h’
‘uint16NDArray’        ‘uint16_array_value’          ‘uint16NDArray.h’
‘uint32NDArray’        ‘uint32_array_value’          ‘uint32NDArray.h’
‘uint64NDArray’        ‘uint64_array_value’          ‘uint64NDArray.h’


File: octave.info,  Node: Character Strings in Oct-Files,  Next: Cell Arrays in Oct-Files,  Prev: Matrices and Arrays in Oct-Files,  Up: Oct-Files

A.1.3 Character Strings in Oct-Files
------------------------------------

A character string in Octave is just a special ‘Array’ class.  Consider
the example:

     #include <octave/oct.h>
     
     DEFUN_DLD (stringdemo, args, , "String Demo")
     {
       if (args.length () != 1)
         print_usage ();
     
       octave_value_list retval;
     
       charMatrix ch = args(0).char_matrix_value ();
     
       retval(1) = octave_value (ch, '\'');  // Single Quote String
     
       octave_idx_type nr = ch.rows ();
     
       for (octave_idx_type i = 0; i < nr / 2; i++)
         {
           std::string tmp = ch.row_as_string (i);
     
           ch.insert (ch.row_as_string (nr-i-1).c_str (), i, 0);
           ch.insert (tmp.c_str (), nr-i-1, 0);
         }
     
       retval(0) = octave_value (ch, '"');  // Double Quote String
     
       return retval;
     }

   An example of the use of this function is

     s0 = ["First String"; "Second String"];
     [s1,s2] = stringdemo (s0)
     ⇒ s1 = Second String
             First String

     ⇒ s2 = First String
             Second String

     typeinfo (s2)
     ⇒ sq_string
     typeinfo (s1)
     ⇒ string

   One additional complication of strings in Octave is the difference
between single quoted and double quoted strings.  To find out if an
‘octave_value’ contains a single or double quoted string use one of the
predicate tests shown below.

     if (args(0).is_sq_string ())
       octave_stdout << "First argument is a single quoted string\n";
     else if (args(0).is_dq_string ())
       octave_stdout << "First argument is a double quoted string\n";

   Note, however, that both types of strings are represented by the
‘charNDArray’ type, and so when assigning to an ‘octave_value’, the type
of string should be specified.  For example:

     octave_value_list retval;
     charNDArray ch;
     ...
     // Create single quoted string
     retval(1) = octave_value (ch);   // default constructor is sq_string
                OR
     retval(1) = octave_value (ch, '\'');  // explicitly create sq_string

     // Create a double quoted string
     retval(0) = octave_value (ch, '"');


File: octave.info,  Node: Cell Arrays in Oct-Files,  Next: Structures in Oct-Files,  Prev: Character Strings in Oct-Files,  Up: Oct-Files

A.1.4 Cell Arrays in Oct-Files
------------------------------

Octave’s cell type is also available from within oct-files.  A cell
array is just an ‘Array’ of ‘octave_value’s, and thus each element of
the cell array can be treated like any other ‘octave_value’.  A simple
example is

     #include <octave/oct.h>
     #include <octave/Cell.h>
     
     DEFUN_DLD (celldemo, args, , "Cell Demo")
     {
       if (args.length () != 1)
         print_usage ();
     
       Cell c = args(0).cell_value ();
     
       octave_value_list retval;
       retval.resize (c.numel ());    // faster code by pre-declaring size
     
       for (octave_idx_type i = 0; i < c.numel (); i++)
         {
           retval(i) = c(i);          // using operator syntax
           //retval(i) = c.elem (i);  // using method syntax
         }
     
       return retval;
     }

   Note that cell arrays are used less often in standard oct-files and
so the ‘Cell.h’ header file must be explicitly included.  The rest of
the example extracts the ‘octave_value’s one by one from the cell array
and returns them as individual output arguments.  For example:

     [b1, b2, b3] = celldemo ({1, [1, 2], "test"})
     ⇒
     b1 =  1
     b2 =

        1   2

     b3 = test


File: octave.info,  Node: Structures in Oct-Files,  Next: Sparse Matrices in Oct-Files,  Prev: Cell Arrays in Oct-Files,  Up: Oct-Files

A.1.5 Structures in Oct-Files
-----------------------------

A structure in Octave is a map between a number of fields represented
and their values.  The Standard Template Library ‘map’ class is used,
with the pair consisting of a ‘std::string’ and an Octave ‘Cell’
variable.

   A simple example demonstrating the use of structures within oct-files
is

     #include <octave/oct.h>
     #include <octave/ov-struct.h>
     
     DEFUN_DLD (structdemo, args, , "Struct Demo")
     {
       if (args.length () != 2)
         print_usage ();
     
       if (! args(0).isstruct ())
         error ("structdemo: ARG1 must be a struct");
     
       octave_scalar_map arg0 = args(0).scalar_map_value ();
       //octave_map arg0 = args(0).map_value ();
     
       if (! args(1).is_string ())
         error ("structdemo: ARG2 must be a character string");
     
       std::string arg1 = args(1).string_value ();
     
       octave_value tmp = arg0.contents (arg1);
       //octave_value tmp = arg0.contents (arg1)(0);
     
       if (! tmp.is_defined ())
         error ("structdemo: struct does not have a field named '%s'\n",
                arg1.c_str ());
     
       octave_scalar_map st;
     
       st.assign ("selected", tmp);
     
       return octave_value (st);
     }

   An example of its use is

     x.a = 1; x.b = "test"; x.c = [1, 2];
     structdemo (x, "b")
     ⇒ selected = test

   The example above specifically uses the ‘octave_scalar_map’ class
which is for representing a single struct.  For structure arrays, the
‘octave_map’ class is used instead.  The commented code shows how the
demo could be modified to handle a structure array.  In that case, the
‘contents’ method returns a ‘Cell’ which may have more than one element.
Therefore, to obtain the underlying ‘octave_value’ in the single struct
example we would write

     octave_value tmp = arg0.contents (arg1)(0);

where the trailing ‘(0)’ is the ‘()’ operator on the ‘Cell’ object.  If
this were a true structure array with multiple elements we could iterate
over the elements using the ‘()’ operator.

   Structures are a relatively complex data container and there are more
functions available in ‘oct-map.h’ which make coding with them easier
than relying on just ‘contents’.


File: octave.info,  Node: Sparse Matrices in Oct-Files,  Next: Accessing Global Variables in Oct-Files,  Prev: Structures in Oct-Files,  Up: Oct-Files

A.1.6 Sparse Matrices in Oct-Files
----------------------------------

There are three classes of sparse objects that are of interest to the
user.

‘SparseMatrix’
     A double precision sparse matrix class

‘SparseComplexMatrix’
     A complex sparse matrix class

‘SparseBoolMatrix’
     A boolean sparse matrix class

   All of these classes inherit from the ‘Sparse<T>’ template class, and
so all have similar capabilities and usage.  The ‘Sparse<T>’ class was
based on Octave’s ‘Array<T>’ class and users familiar with Octave’s
‘Array’ classes will be comfortable with the use of the sparse classes.

   The sparse classes will not be entirely described in this section,
due to their similarity with the existing ‘Array’ classes.  However,
there are a few differences due the nature of sparse objects, and these
will be described.  First, although it is fundamentally possible to have
N-dimensional sparse objects, the Octave sparse classes do not allow
them at this time; All instances of the sparse classes *must* be
2-dimensional.  This means that ‘SparseMatrix’ is actually more similar
to Octave’s ‘Matrix’ class than it is to the ‘NDArray’ class.

* Menu:

* Array and Sparse Class Differences::
* Creating Sparse Matrices in Oct-Files::
* Using Sparse Matrices in Oct-Files::


File: octave.info,  Node: Array and Sparse Class Differences,  Next: Creating Sparse Matrices in Oct-Files,  Up: Sparse Matrices in Oct-Files

A.1.6.1 Array and Sparse Class Differences
..........................................

The number of elements in a sparse matrix is considered to be the number
of nonzero elements, rather than the product of the dimensions.
Therefore,

     SparseMatrix sm;
     ...
     int nnz = sm.nelem ();

returns the number of nonzero elements (like the interpreter function
‘nnz’).  If the user really requires the number of elements in the
matrix, including the nonzero elements, they should use ‘numel’ rather
than ‘nelem’.  Note that for very large matrices, where the product of
the two dimensions is larger than the representation of an unsigned int,
‘numel’ can overflow.  An example is ‘speye (1e6)’ which will create a
matrix with a million rows and columns, but only a million nonzero
elements.  In this case, the number of rows multiplied by the number of
columns is more than two hundred times the maximum value that can be
represented by an unsigned 32-bit int.  The use of ‘numel’ should,
therefore, be avoided unless it is known that it will not overflow.

   Extreme care is also required when using the ‘elem’ method or the
‘()’ operator which perform essentially the same function.  The reason
is that if a sparse object is non-const, then Octave will assume that a
request for a zero element in a sparse matrix is in fact a request to
create this element so it can be filled.  Therefore, a piece of code
like

     SparseMatrix sm;
     ...
     for (int j = 0; j < nc; j++)
       for (int i = 0; i < nr; i++)
         std::cerr << " (" << i << "," << j << "): " << sm(i,j) << "\n";

is a great way of turning a sparse matrix into a dense one, and a very
slow way at that since it reallocates the sparse object for each zero
element in the matrix.

   A simple way of preventing the above from happening is to create a
temporary constant version of the sparse matrix.  Note that only the
container for the sparse matrix will be copied, while the actual
representation of the data will be shared between the two versions of
the sparse matrix; This is not a costly operation.  The example above,
re-written to prevent sparse-to-dense conversion, is

     SparseMatrix sm;
     ...
     const SparseMatrix tmp (sm);
     for (int j = 0; j < nc; j++)
       for (int i = 0; i < nr; i++)
         std::cerr << " (" << i << "," << j << "): " << tmp(i,j) << "\n";

   Finally, because the sparse types aren’t represented by a contiguous
block of memory, the ‘fortran_vec’ method of ‘Array<T>’ is not
available.  It is, however, replaced by three separate methods ‘ridx’,
‘cidx’, and ‘data’, that access the raw compressed column format that
Octave sparse matrices are stored in.  These methods can be used in a
manner similar to ‘elem’ to allow the matrix to be accessed or filled.
However, it is up to the user to respect the sparse matrix compressed
column format or the matrix will become corrupted.


File: octave.info,  Node: Creating Sparse Matrices in Oct-Files,  Next: Using Sparse Matrices in Oct-Files,  Prev: Array and Sparse Class Differences,  Up: Sparse Matrices in Oct-Files

A.1.6.2 Creating Sparse Matrices in Oct-Files
.............................................

There are two useful strategies for creating a sparse matrix.  The first
is to create three vectors representing the row index, column index, and
data values, and from these create the matrix.  The second alternative
is to create a sparse matrix with the appropriate amount of space, and
then fill in the values.  Both techniques have their advantages and
disadvantages.

   Below is an example of creating a small sparse matrix using the first
technique

     int nz, nr, nc;
     nz = 4, nr = 3, nc = 4;

     ColumnVector ridx (nz);
     ColumnVector cidx (nz);
     ColumnVector data (nz);

     ridx(0) = 1; cidx(0) = 1; data(0) = 1;
     ridx(1) = 2; cidx(1) = 2; data(1) = 2;
     ridx(2) = 2; cidx(2) = 4; data(2) = 3;
     ridx(3) = 3; cidx(3) = 4; data(3) = 4;
     SparseMatrix sm (data, ridx, cidx, nr, nc);

which creates the matrix given in section *note Storage of Sparse
Matrices::.  Note that the compressed matrix format is not used at the
time of the creation of the matrix itself, but is used internally.

   As discussed in the chapter on Sparse Matrices, the values of the
sparse matrix are stored in increasing column-major ordering.  Although
the data passed by the user need not respect this requirement,
pre-sorting the data will significantly speed up creation of the sparse
matrix.

   The disadvantage of this technique for creating a sparse matrix is
that there is a brief time when two copies of the data exist.  For
extremely memory constrained problems this may not be the best technique
for creating a sparse matrix.

   The alternative is to first create a sparse matrix with the desired
number of nonzero elements and then later fill those elements in.
Sample code:

     int nz, nr, nc;
     nz = 4, nr = 3, nc = 4;
     SparseMatrix sm (nr, nc, nz);
     sm(0,0) = 1; sm(0,1) = 2; sm(1,3) = 3; sm(2,3) = 4;

   This creates the same matrix as previously.  Again, although not
strictly necessary, it is significantly faster if the sparse matrix is
created and the elements are added in column-major ordering.  The reason
for this is that when elements are inserted at the end of the current
list of known elements then no element in the matrix needs to be moved
to allow the new element to be inserted; Only the column indices need to
be updated.

   There are a few further points to note about this method of creating
a sparse matrix.  First, it is possible to create a sparse matrix with
fewer elements than are actually inserted in the matrix.  Therefore,

     int nr, nc;
     nr = 3, nc = 4;
     SparseMatrix sm (nr, nc, 0);
     sm(0,0) = 1; sm(0,1) = 2; sm(1,3) = 3; sm(2,3) = 4;

is perfectly valid.  However, it is a very bad idea because as each new
element is added to the sparse matrix the matrix needs to request more
space and reallocate memory.  This is an expensive operation that will
significantly slow this means of creating a sparse matrix.  It is
possible to create a sparse matrix with excess storage, so having NZ
greater than 4 in this example is also valid.  The disadvantage is that
the matrix occupies more memory than strictly needed.

   Of course, it is not always possible to know the number of nonzero
elements prior to filling a matrix.  For this reason the additional
unused storage of a sparse matrix can be removed after its creation with
the ‘maybe_compress’ function.  In addition to deallocating unused
storage, ‘maybe_compress’ can also remove zero elements from the matrix.
The removal of zero elements from the matrix is controlled by setting
the argument of the ‘maybe_compress’ function to be ‘true’.  However,
the cost of removing the zeros is high because it implies re-sorting the
elements.  If possible, it is better for the user to avoid adding the
unnecessary zeros in the first place.  An example of the use of
‘maybe_compress’ is

     int nz, nr, nc;
     nz = 6, nr = 3, nc = 4;

     SparseMatrix sm1 (nr, nc, nz);
     sm1(0,0) = 1; sm1(0,1) = 2; sm1(1,3) = 3; sm1(2,3) = 4;
     sm1.maybe_compress ();   // No zero elements were added

     SparseMatrix sm2 (nr, nc, nz);
     sm2(0,0) = 1; sm2(0,1) = 2; sm(0,2) = 0; sm(1,2) = 0;
     sm1(1,3) = 3; sm1(2,3) = 4;
     sm2.maybe_compress (true);  // Zero elements were added

   The use of the ‘maybe_compress’ function should be avoided if
possible as it will slow the creation of the matrix.

   A third means of creating a sparse matrix is to work directly with
the data in compressed row format.  An example of this advanced
technique might be

     octave_value arg;
     ...
     int nz, nr, nc;
     nz = 6, nr = 3, nc = 4;   // Assume we know the max # nz
     SparseMatrix sm (nr, nc, nz);
     Matrix m = arg.matrix_value ();

     int ii = 0;
     sm.cidx (0) = 0;
     for (int j = 1; j < nc; j++)
       {
         for (int i = 0; i < nr; i++)
           {
             double tmp = m(i,j);
             if (tmp != 0.)
               {
                 sm.data(ii) = tmp;
                 sm.ridx(ii) = i;
                 ii++;
               }
           }
         sm.cidx(j+1) = ii;
      }
     sm.maybe_compress ();  // If don't know a priori the final # of nz.

which is probably the most efficient means of creating a sparse matrix.

   Finally, it may sometimes arise that the amount of storage initially
created is insufficient to completely store the sparse matrix.
Therefore, the method ‘change_capacity’ exists to reallocate the sparse
memory.  The above example would then be modified as

     octave_value arg;
     ...
     int nz, nr, nc;
     nz = 6, nr = 3, nc = 4;   // Guess the number of nz elements
     SparseMatrix sm (nr, nc, nz);
     Matrix m = arg.matrix_value ();

     int ii = 0;
     sm.cidx (0) = 0;
     for (int j = 1; j < nc; j++)
       {
         for (int i = 0; i < nr; i++)
           {
             double tmp = m(i,j);
             if (tmp != 0.)
               {
                 if (ii == nz)
                   {
                     nz += 2;   // Add 2 more elements
                     sm.change_capacity (nz);
                   }
                 sm.data(ii) = tmp;
                 sm.ridx(ii) = i;
                 ii++;
               }
           }
         sm.cidx(j+1) = ii;
      }
     sm.maybe_compress ();  // If don't know a priori the final # of nz.

   Note that both increasing and decreasing the number of nonzero
elements in a sparse matrix is expensive as it involves memory
reallocation.  Also because parts of the matrix, though not its
entirety, exist as old and new copies at the same time, additional
memory is needed.  Therefore, if possible avoid changing capacity.


File: octave.info,  Node: Using Sparse Matrices in Oct-Files,  Prev: Creating Sparse Matrices in Oct-Files,  Up: Sparse Matrices in Oct-Files

A.1.6.3 Using Sparse Matrices in Oct-Files
..........................................

Most of the same operators and functions for sparse matrices that are
available from the Octave interpreter are also available within
oct-files.  The basic means of extracting a sparse matrix from an
‘octave_value’, and returning it as an ‘octave_value’, can be seen in
the following example.

     octave_value_list retval;

     SparseMatrix sm = args(0).sparse_matrix_value ();
     SparseComplexMatrix scm = args(1).sparse_complex_matrix_value ();
     SparseBoolMatrix sbm = args(2).sparse_bool_matrix_value ();
     ...
     retval(2) = sbm;
     retval(1) = scm;
     retval(0) = sm;

   The conversion to an ‘octave_value’ is handled by the sparse
‘octave_value’ constructors, and so no special care is needed.


File: octave.info,  Node: Accessing Global Variables in Oct-Files,  Next: Calling Octave Functions from Oct-Files,  Prev: Sparse Matrices in Oct-Files,  Up: Oct-Files

A.1.7 Accessing Global Variables in Oct-Files
---------------------------------------------

Global variables allow variables in the global scope to be accessed.
Global variables can be accessed within oct-files by using the support
functions ‘global_varval’ and ‘global_assign’ from the current
interpreter’s symbol table.  Both functions take as first argument a
string representing the variable name to be obtained or assigned.  The
second argument of ‘global_assign’ is the value to be assigned.  An
example of the use of these two functions is

     #include <octave/oct.h>
     #include <octave/interpreter.h>
     
     DEFMETHOD_DLD (globaldemo, interp, args, , "Global Demo")
     {
       if (args.length () != 1)
         print_usage ();
     
       octave_value retval;
     
       std::string s = args(0).string_value ();
     
       octave::symbol_table& symtab = interp.get_symbol_table ();
     
       octave_value tmp = symtab.global_varval (s);
     
       if (tmp.is_defined ())
         retval = tmp;
       else
         retval = "Global variable not found";
     
       symtab.global_assign ("a", 42.0);
     
       return retval;
     }

   An example of its use is

     global a b
     b = 10;
     globaldemo ("b")
     ⇒ 10
     globaldemo ("c")
     ⇒ "Global variable not found"
     num2str (a)
     ⇒ 42


File: octave.info,  Node: Calling Octave Functions from Oct-Files,  Next: Calling External Code from Oct-Files,  Prev: Accessing Global Variables in Oct-Files,  Up: Oct-Files

A.1.8 Calling Octave Functions from Oct-Files
---------------------------------------------

There is often a need to be able to call another Octave function from
within an oct-file, and there are many examples of such within Octave
itself.  For example, the ‘quad’ function is an oct-file that calculates
the definite integral by quadrature over a user-supplied function.

   There are also many ways in which a function could be given as input.
It might be passed as one of

  1. Function Handle

  2. Anonymous Function Handle

  3. String

   The code below demonstrates all four methods of passing a function to
an oct-file.

     #include <octave/oct.h>
     #include <octave/parse.h>
     
     DEFMETHOD_DLD (funcdemo, interp, args, nargout, "Function Demo")
     {
       int nargin = args.length ();
     
       if (nargin < 2)
         print_usage ();
     
       octave_value_list newargs;
     
       for (octave_idx_type i = nargin - 1; i > 0; i--)
         newargs(i-1) = args(i);
     
       octave_value_list retval;
     
       if (args(0).is_function_handle () || args(0).is_inline_function ()
           || args(0).is_string ())
         retval = interp.feval (args(0), newargs, nargout);
       else
         error ("funcdemo: INPUT must be string, inline, or function handle");
     
       return retval;
     }

   The first input to the demonstration code is a user-supplied function
and the remaining arguments are all passed to the function.

     funcdemo (@sin, 1)
     ⇒ 0.84147
     funcdemo (@(x) sin (x), 1)
     ⇒ 0.84147
     funcdemo ("sin", 1)
     ⇒ 0.84147
     funcdemo (@atan2, 1, 1)
     ⇒ 0.78540

   When the user function is passed as a string the treatment of the
function is different.  In some cases it is necessary to have the user
supplied function as an ‘octave_function’ object.  In that case the
string argument can be used to create a temporary function as
demonstrated below.

     std::octave fcn_name = unique_symbol_name ("__fcn__");
     std::string fcode = "function y = ";
     fcode.append (fcn_name);
     fcode.append ("(x) y = ");
     fcn = extract_function (args(0), "funcdemo", fcn_name,
                             fcode, "; endfunction");
     ...
     if (fcn_name.length ())
       clear_function (fcn_name);

   There are two important things to know in this case.  First, the
number of input arguments to the user function is fixed, and in the
above example is a single argument.  Second, to avoid leaving the
temporary function in the Octave symbol table it should be cleared after
use.  Also, by convention all internal function names begin and end with
the character sequence ‘__’.


File: octave.info,  Node: Calling External Code from Oct-Files,  Next: Allocating Local Memory in Oct-Files,  Prev: Calling Octave Functions from Oct-Files,  Up: Oct-Files

A.1.9 Calling External Code from Oct-Files
------------------------------------------

Linking external C code to Octave is relatively simple, as the C
functions can easily be called directly from C++.  One possible issue is
that the declarations of the external C functions may need to be
explicitly defined as C functions to the compiler.  If the declarations
of the external C functions are in the header ‘foo.h’, then the tactic
to ensure that the C++ compiler treats these declarations as C code is

     #ifdef __cplusplus
     extern "C"
     {
     #endif
     #include "foo.h"
     #ifdef __cplusplus
     }  /* end extern "C" */
     #endif

   Calling Fortran code, however, can pose more difficulties.  This is
due to differences in the manner in which compilers treat the linking of
Fortran code with C or C++ code.  Octave supplies several macros that
allow consistent behavior across a number of compilers.

   The underlying Fortran code should use the ‘XSTOPX’ function to
replace the Fortran ‘STOP’ function.  ‘XSTOPX’ uses the Octave exception
handler to treat failing cases in the Fortran code explicitly.  Note
that Octave supplies its own replacement BLAS ‘XERBLA’ function, which
uses ‘XSTOPX’.

   If the code calls ‘XSTOPX’, then the ‘F77_XFCN’ macro should be used
to call the underlying Fortran function.  The Fortran exception state
can then be checked with the global variable
‘f77_exception_encountered’.  If ‘XSTOPX’ will not be called, then the
‘F77_FCN’ macro should be used instead to call the Fortran code.

   There is no great harm in using ‘F77_XFCN’ in all cases, except that
for Fortran code that is short running and executes a large number of
times, there is potentially an overhead in doing so.  However, if
‘F77_FCN’ is used with code that calls ‘XSTOP’, Octave can generate a
segmentation fault.

   An example of the inclusion of a Fortran function in an oct-file is
given in the following example, where the C++ wrapper is

     #include <octave/oct.h>
     #include <octave/f77-fcn.h>
     
     extern "C"
     {
       F77_RET_T
       F77_FUNC (fortransub, FORTSUB)
         (const F77_INT&, F77_DBLE*, F77_CHAR_ARG_DECL F77_CHAR_ARG_LEN_DECL);
     }
     
     DEFUN_DLD (fortrandemo, args, , "Fortran Demo")
     {
       if (args.length () != 1)
         print_usage ();
     
       NDArray a = args(0).array_value ();
     
       double *av = a.fortran_vec ();
       octave_idx_type na = a.numel ();
     
       OCTAVE_LOCAL_BUFFER (char, ctmp, 128);
     
       F77_XFCN (fortransub, FORTSUB,
                 (na, av, ctmp F77_CHAR_ARG_LEN (128)));
     
       return ovl (a, std::string (ctmp));
     }

and the Fortran function is

           subroutine fortransub (n, a, s)
           implicit none
           character*(*) s
           real*8 a(*)
           integer*4 i, n, ioerr
           do i = 1, n
             if (a(i) .eq. 0d0) then
               call xstopx ('fortransub: divide by zero')
             else
               a(i) = 1d0 / a(i)
             endif
           enddo
           write (unit = s, fmt = '(a,i3,a,a)', iostat = ioerr)
          $       'There are ', n,
          $       ' values in the input vector', char(0)
           if (ioerr .ne. 0) then
             call xstopx ('fortransub: error writing string')
           endif
           return
           end

   This example demonstrates most of the features needed to link to an
external Fortran function, including passing arrays and strings, as well
as exception handling.  Both the Fortran and C++ files need to be
compiled in order for the example to work.

     mkoctfile fortrandemo.cc fortransub.f
     [b, s] = fortrandemo (1:3)
     ⇒
       b = 1.00000   0.50000   0.33333
       s = There are   3 values in the input vector
     [b, s] = fortrandemo (0:3)
     error: fortrandemo: fortransub: divide by zero


File: octave.info,  Node: Allocating Local Memory in Oct-Files,  Next: Input Parameter Checking in Oct-Files,  Prev: Calling External Code from Oct-Files,  Up: Oct-Files

A.1.10 Allocating Local Memory in Oct-Files
-------------------------------------------

Allocating memory within an oct-file might seem easy, as the C++
new/delete operators can be used.  However, in that case great care must
be taken to avoid memory leaks.  The preferred manner in which to
allocate memory for use locally is to use the ‘OCTAVE_LOCAL_BUFFER’
macro.  An example of its use is

     OCTAVE_LOCAL_BUFFER (double, tmp, len)

that returns a pointer ‘tmp’ of type ‘double *’ of length ‘len’.

   In this case, Octave itself will worry about reference counting and
variable scope and will properly free memory without programmer
intervention.


File: octave.info,  Node: Input Parameter Checking in Oct-Files,  Next: Exception and Error Handling in Oct-Files,  Prev: Allocating Local Memory in Oct-Files,  Up: Oct-Files

A.1.11 Input Parameter Checking in Oct-Files
--------------------------------------------

Because oct-files are compiled functions they open up the possibility of
crashing Octave through careless function calls or memory faults.  It is
quite important that each and every function have a sufficient level of
parameter checking to ensure that Octave behaves well.

   The minimum requirement, as previously discussed, is to check the
number of input arguments before using them to avoid referencing a
nonexistent argument.  However, in some cases this might not be
sufficient as the underlying code imposes further constraints.  For
example, an external function call might be undefined if the input
arguments are not integers, or if one of the arguments is zero, or if
the input is complex and a real value was expected.  Therefore,
oct-files often need additional input parameter checking.

   There are several functions within Octave that can be useful for the
purposes of parameter checking.  These include the methods of the
‘octave_value’ class like ‘is_real_matrix’, ‘is_numeric_type’, etc.
(see ‘ov.h’).  Often, with a knowledge of the Octave m-file language,
you can guess at what the corresponding C++ routine will.  In addition
there are some more specialized input validation functions of which a
few are demonstrated below.

     #include <octave/oct.h>
     
     DEFUN_DLD (paramdemo, args, nargout, "Parameter Check Demo")
     {
       if (args.length () != 1)
         print_usage ();
     
       NDArray m = args(0).array_value ();
     
       double min_val = -10.0;
       double max_val = 10.0;
     
       octave_stdout << "Properties of input array:\n";
     
       if (m.any_element_is_negative ())
         octave_stdout << "  includes negative values\n";
     
       if (m.any_element_is_inf_or_nan ())
         octave_stdout << "  includes Inf or NaN values\n";
     
       if (m.any_element_not_one_or_zero ())
         octave_stdout << "  includes other values than 1 and 0\n";
     
       if (m.all_elements_are_int_or_inf_or_nan ())
         octave_stdout << "  includes only int, Inf or NaN values\n";
     
       if (m.all_integers (min_val, max_val))
         octave_stdout << "  includes only integers in [-10,10]\n";
     
       return octave_value_list ();
     }

An example of its use is:

     paramdemo ([1, 2, NaN, Inf])
     ⇒ Properties of input array:
          includes Inf or NaN values
          includes other values than 1 and 0
          includes only int, Inf or NaN values


File: octave.info,  Node: Exception and Error Handling in Oct-Files,  Next: Documentation and Testing of Oct-Files,  Prev: Input Parameter Checking in Oct-Files,  Up: Oct-Files

A.1.12 Exception and Error Handling in Oct-Files
------------------------------------------------

Another important feature of Octave is its ability to react to the user
typing <Control-C> during extended calculations.  This ability is based
on the C++ exception handler, where memory allocated by the C++
new/delete methods is automatically released when the exception is
treated.  When writing an oct-file which may run for a long time the
programmer must periodically use the macro ‘OCTAVE_QUIT’, in order to
allow Octave to check and possibly respond to a user typing <Control-C>.
For example:

     for (octave_idx_type i = 0; i < a.nelem (); i++)
       {
         OCTAVE_QUIT;
         b.elem (i) = 2. * a.elem (i);
       }

   The presence of the ‘OCTAVE_QUIT’ macro in the inner loop allows
Octave to detect and acknowledge a <Control-C> key sequence.  Without
this macro, the user must either wait for the oct-file function to
return before the interrupt is processed, or the user must press
<Control-C> three times which will force Octave to exit completely.

   The ‘OCTAVE_QUIT’ macro does impose a very small performance penalty;
For loops that are known to be small it may not make sense to include
‘OCTAVE_QUIT’.

   When creating an oct-file that uses an external library, the function
might spend a significant portion of its time in the external library.
It is not generally possible to use the ‘OCTAVE_QUIT’ macro in this
case.  The alternative code in this case is

     BEGIN_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;
     ...  some code that calls a "foreign" function ...
     END_INTERRUPT_IMMEDIATELY_IN_FOREIGN_CODE;

   The disadvantage of this is that if the foreign code allocates any
memory internally, then this memory might be lost during an interrupt,
without being deallocated.  Therefore, ideally Octave itself should
allocate any memory that is needed by the foreign code, with either the
‘fortran_vec’ method or the ‘OCTAVE_LOCAL_BUFFER’ macro.

   The Octave ‘unwind_protect’ mechanism (*note The unwind_protect
Statement::) can also be used in oct-files.  In conjunction with the
exception handling of Octave, it ensures that certain recovery code is
always run even if an exception occurs.  An example of the use of this
mechanism is

     #include <octave/oct.h>
     #include <octave/unwind-prot.h>
     
     void
     my_err_handler (const char *fmt, ...)
     {
       // Do nothing!!
     }
     
     void
     my_err_with_id_handler (const char *id, const char *fmt, ...)
     {
       // Do nothing!!
     }
     
     DEFUN_DLD (unwinddemo, args, nargout, "Unwind Demo")
     {
       if (args.length () < 2)
         print_usage ();
     
       NDArray a = args(0).array_value ();
       NDArray b = args(1).array_value ();
     
       // Declare unwind_protect frame which lasts as long as
       // the variable frame has scope.
       octave::unwind_protect frame;
       frame.add_fcn (set_liboctave_warning_handler,
                      current_liboctave_warning_handler);
     
       frame.add_fcn (set_liboctave_warning_with_id_handler,
                      current_liboctave_warning_with_id_handler);
     
       set_liboctave_warning_handler (my_err_handler);
       set_liboctave_warning_with_id_handler (my_err_with_id_handler);
     
       return octave_value (quotient (a, b));
     }

   As can be seen in the example:

     unwinddemo (1, 0)
     ⇒ Inf
     1 / 0
     ⇒ warning: division by zero
        Inf

   The warning for division by zero (and in fact all warnings) are
disabled in the ‘unwinddemo’ function.


File: octave.info,  Node: Documentation and Testing of Oct-Files,  Prev: Exception and Error Handling in Oct-Files,  Up: Oct-Files

A.1.13 Documentation and Testing of Oct-Files
---------------------------------------------

The documentation for an oct-file is contained in the fourth string
parameter of the ‘DEFUN_DLD’ macro.  This string can be formatted in the
same manner as the help strings for user functions, however there are
some issues that are particular to the formatting of help strings within
oct-files.

   The major issue is that the help string will typically be longer than
a single line of text, and so the formatting of long multi-line help
strings needs to be taken into account.  There are several possible
solutions, but the most common is illustrated in the following example,

     DEFUN_DLD (do_what_i_want, args, nargout,
       "-*- texinfo -*-\n\
     @deftypefn {} {} do_what_i_say (@var{n})\n\
     A function that does what the user actually wants rather\n\
     than what they requested.\n\
     @end deftypefn")
     {
     ...
     }

where each line of text is terminated by ‘\n\’ which is an embedded
newline in the string together with a C++ string continuation character.
Note that the final ‘\’ must be the last character on the line.

   Octave also includes the ability to embed test and demonstration code
for a function within the code itself (*note Test and Demo Functions::).
This can be used from within oct-files (or in fact any file) with
certain provisos.  First, the test and demo functions of Octave look for
‘%!’ as the first two characters of a line to identify test and
demonstration code.  This is a requirement for oct-files as well.  In
addition, the test and demonstration code must be wrapped in a comment
block to avoid it being interpreted by the compiler.  Finally, the
Octave test and demonstration code must have access to the original
source code of the oct-file—not just the compiled code—as the tests are
stripped from the compiled code.  An example in an oct-file might be

     /*
     %!assert (sin ([1,2]), [sin(1),sin(2)])
     %!error (sin ())
     %!error (sin (1,1))
     */


File: octave.info,  Node: Mex-Files,  Next: Standalone Programs,  Prev: Oct-Files,  Up: External Code Interface

A.2 Mex-Files
=============

Octave includes an interface to allow legacy mex-files to be compiled
and used with Octave.  This interface can also be used to share compiled
code between Octave and MATLAB users.  However, as mex-files expose
MATLAB’s internal API, and the internal structure of Octave is
different, a mex-file can never have the same performance in Octave as
the equivalent oct-file.  In particular, to support the manner in which
variables are passed to mex functions there are a significant number of
additional copies of memory blocks when invoking or returning from a
mex-file function.  For this reason, it is recommended that any new code
be written with the oct-file interface previously discussed.

* Menu:

* Getting Started with Mex-Files::
* Working with Matrices and Arrays in Mex-Files::
* Character Strings in Mex-Files::
* Cell Arrays with Mex-Files::
* Structures with Mex-Files::
* Sparse Matrices with Mex-Files::
* Calling Other Functions in Mex-Files::


File: octave.info,  Node: Getting Started with Mex-Files,  Next: Working with Matrices and Arrays in Mex-Files,  Up: Mex-Files

A.2.1 Getting Started with Mex-Files
------------------------------------

The basic command to build a mex-file is either ‘mkoctfile --mex’ or
‘mex’.  The first command can be used either from within Octave or from
the command line.  To avoid issues with MATLAB’s own ‘mex’ command, the
use of the command ‘mex’ is limited to within Octave.  Compiled
mex-files have the extension ‘.mex’.

 -- : mex [-options] file ...
 -- : ‘status’ = mex (...)
     Compile source code written in C, C++, or Fortran, to a MEX file.

     STATUS is the return status of the ‘mkoctfile’ function.

     If the compilation fails, and the output argument is not requested,
     an error is raised.  If the programmer requests STATUS, however,
     Octave will merely issue a warning and it is the programmer’s
     responsibility to verify the command was successful.

     This is equivalent to ‘mkoctfile --mex [-options] file’.

     See also: *note mkoctfile: XREFmkoctfile, *note mexext: XREFmexext.

 -- : mexext ()
     Return the filename extension used for MEX files.

     See also: *note mex: XREFmex.

   Consider the following short example:

     #include "mex.h"
     
     void
     mexFunction (int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
     {
       mexPrintf ("Hello, World!\n");
     
       mexPrintf ("I have %d inputs and %d outputs\n", nrhs, nlhs);
     
       /* Return empty matrices for any outputs */
       int i;
       for (i = 0; i < nlhs; i++)
         plhs[i] = mxCreateDoubleMatrix (0, 0, mxREAL);
     }

   The first line ‘#include "mex.h"’ makes available all of the
definitions necessary for a mex-file.  One important difference between
Octave and MATLAB is that the header file "matrix.h" is implicitly
included through the inclusion of "mex.h".  This is necessary to avoid a
conflict with the Octave file "Matrix.h" for operating systems and
compilers that don’t distinguish between filenames in upper and lower
case.

   The entry point into the mex-file is defined by ‘mexFunction’.  The
function takes four arguments:

  1. The number of return arguments (# of left-hand side args).

  2. An array of pointers to return arguments.

  3. The number of input arguments (# of right-hand side args).

  4. An array of pointers to input arguments.

   Note that the function name definition is not explicitly included in
‘mexFunction’ and so there can only be a single ‘mexFunction’ entry
point per file.  Instead, the name of the function as seen in Octave is
determined by the name of the mex-file itself minus the extension.  If
the above function is in the file ‘myhello.c’, it can be compiled with

     mkoctfile --mex myhello.c

which creates a file ‘myhello.mex’.  The function can then be run from
Octave as

     myhello (1,2,3)
     ⇒ Hello, World!
     ⇒ I have 3 inputs and 0 outputs

   It should be noted that the mex-file contains no help string.  To
document mex-files, there should exist an m-file in the same directory
as the mex-file itself.  Taking the above as an example, there would
need to be a file ‘myhello.m’ which might contain the text

     %MYHELLO Simple test of the functionality of a mex-file.

   In this case, the function that will be executed within Octave will
be given by the mex-file, while the help string will come from the
m-file.  This can also be useful to allow a sample implementation of the
mex-file within the Octave language itself for testing purposes.

   Although there cannot be multiple entry points in a single mex-file,
one can use the ‘mexFunctionName’ function to determine what name the
mex-file was called with.  This can be used to alter the behavior of the
mex-file based on the function name.  For example, if

     #include "mex.h"
     
     void
     mexFunction (int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
     {
       const char *nm;
     
       nm = mexFunctionName ();
       mexPrintf ("You called function: %s\n", nm);
       if (strcmp (nm, "myfunc") == 0)
         mexPrintf ("This is the principal function\n", nm);
     
       return;
     }

is in the file ‘myfunc.c’, and is compiled with

     mkoctfile --mex myfunc.c
     ln -s myfunc.mex myfunc2.mex

then as can be seen by

     myfunc ()
     ⇒ You called function: myfunc
         This is the principal function
     myfunc2 ()
     ⇒ You called function: myfunc2

the behavior of the mex-file can be altered depending on the function’s
name.

   Although the user should only include ‘mex.h’ in their code, Octave
declares additional functions, typedefs, etc., available to the user to
write mex-files in the headers ‘mexproto.h’ and ‘mxarray.h’.


File: octave.info,  Node: Working with Matrices and Arrays in Mex-Files,  Next: Character Strings in Mex-Files,  Prev: Getting Started with Mex-Files,  Up: Mex-Files

A.2.2 Working with Matrices and Arrays in Mex-Files
---------------------------------------------------

The basic mex type of all variables is ‘mxArray’.  Any object, such as a
matrix, cell array, or structure, is stored in this basic type.
‘mxArray’ serves essentially the same purpose as the ‘octave_value’
class in oct-files in that it acts as a container for all the more
specialized types.

   The ‘mxArray’ structure contains at a minimum, the name of the
variable it represents, its dimensions, its type, and whether the
variable is real or complex.  It can also contain a number of additional
fields depending on the type of the ‘mxArray’.  There are a number of
functions to create ‘mxArray’ structures, including
‘mxCreateDoubleMatrix’, ‘mxCreateCellArray’, ‘mxCreateSparse’, and the
generic ‘mxCreateNumericArray’.

   The basic function to access the data in an array is ‘mxGetPr’.
Because the mex interface assumes that real and imaginary parts of a
complex array are stored separately, there is an equivalent function
‘mxGetPi’ that gets the imaginary part.  Both of these functions are
only for use with double precision matrices.  The generic functions
‘mxGetData’ and ‘mxGetImagData’ perform the same operation for all
matrix types.  For example:

     mxArray *m;
     mwSize *dims;
     UINT32_T *pr;

     dims = (mwSize *) mxMalloc (2 * sizeof (mwSize));
     dims[0] = 2; dims[1] = 2;
     m = mxCreateNumericArray (2, dims, mxUINT32_CLASS, mxREAL);
     pr = (UINT32_T *) mxGetData (m);

   There are also the functions ‘mxSetPr’, etc., that perform the
inverse, and set the data of an array to use the block of memory pointed
to by the argument of ‘mxSetPr’.

   Note the type ‘mwSize’ used above, and also ‘mwIndex’, are defined as
the native precision of the indexing in Octave on the platform on which
the mex-file is built.  This allows both 32- and 64-bit platforms to
support mex-files.  ‘mwSize’ is used to define array dimensions and the
maximum number or elements, while ‘mwIndex’ is used to define indexing
into arrays.

   An example that demonstrates how to work with arbitrary real or
complex double precision arrays is given by the file ‘mypow2.c’ shown
below.

     #include "mex.h"
     
     void
     mexFunction (int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
     {
       mwSize n;
       mwIndex i;
       double *vri, *vro;
     
       if (nrhs != 1 || ! mxIsDouble (prhs[0]))
         mexErrMsgTxt ("ARG1 must be a double matrix");
     
       n = mxGetNumberOfElements (prhs[0]);
       plhs[0] = mxCreateNumericArray (mxGetNumberOfDimensions (prhs[0]),
                                       mxGetDimensions (prhs[0]),
                                       mxGetClassID (prhs[0]),
                                       mxIsComplex (prhs[0]));
       vri = mxGetPr (prhs[0]);
       vro = mxGetPr (plhs[0]);
     
       if (mxIsComplex (prhs[0]))
         {
           double *vii, *vio;
           vii = mxGetPi (prhs[0]);
           vio = mxGetPi (plhs[0]);
     
           for (i = 0; i < n; i++)
             {
               vro[i] = vri[i] * vri[i] - vii[i] * vii[i];
               vio[i] = 2 * vri[i] * vii[i];
             }
         }
       else
         {
           for (i = 0; i < n; i++)
             vro[i] = vri[i] * vri[i];
         }
     }

An example of its use is

     b = randn (4,1) + 1i * randn (4,1);
     all (b.^2 == mypow2 (b))
     ⇒ 1

   The example above uses the functions ‘mxGetDimensions’,
‘mxGetNumberOfElements’, and ‘mxGetNumberOfDimensions’ to work with the
dimensions of multi-dimensional arrays.  The functions ‘mxGetM’, and
‘mxGetN’ are also available to find the number of rows and columns in a
2-D matrix (MxN matrix).


File: octave.info,  Node: Character Strings in Mex-Files,  Next: Cell Arrays with Mex-Files,  Prev: Working with Matrices and Arrays in Mex-Files,  Up: Mex-Files

A.2.3 Character Strings in Mex-Files
------------------------------------

As mex-files do not make the distinction between single and double
quoted strings that Octave does, there is perhaps less complexity in the
use of strings and character matrices.  An example of their use that
parallels the demo in ‘stringdemo.cc’ is given in the file ‘mystring.c’,
as shown below.

     #include <string.h>
     #include "mex.h"
     
     void
     mexFunction (int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
     {
       mwSize m, n;
       mwIndex i, j;
       mxChar *pi, *po;
     
       if (nrhs != 1 || ! mxIsChar (prhs[0])
           || mxGetNumberOfDimensions (prhs[0]) > 2)
         mexErrMsgTxt ("ARG1 must be a char matrix");
     
       m = mxGetM (prhs[0]);
       n = mxGetN (prhs[0]);
       pi = mxGetChars (prhs[0]);
       plhs[0] = mxCreateNumericMatrix (m, n, mxCHAR_CLASS, mxREAL);
       po = mxGetChars (plhs[0]);
     
       for (j = 0; j < n; j++)
         for (i = 0; i < m; i++)
           po[j*m + m - 1 - i] = pi[j*m + i];
     }

An example of its expected output is

     mystring (["First String"; "Second String"])
     ⇒ Second String
        First String

   Other functions in the mex interface for handling character strings
are ‘mxCreateString’, ‘mxArrayToString’, and
‘mxCreateCharMatrixFromStrings’.  In a mex-file, a character string is
considered to be a vector rather than a matrix.  This is perhaps an
arbitrary distinction as the data in the ‘mxArray’ for the matrix is
consecutive in any case.


File: octave.info,  Node: Cell Arrays with Mex-Files,  Next: Structures with Mex-Files,  Prev: Character Strings in Mex-Files,  Up: Mex-Files

A.2.4 Cell Arrays with Mex-Files
--------------------------------

One can perform exactly the same operations on Cell arrays in mex-files
as in oct-files.  An example that duplicates the function of the
‘celldemo.cc’ oct-file in a mex-file is given by ‘mycell.c’ as shown
below.

     #include "mex.h"
     
     void
     mexFunction (int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
     {
       mwSize n;
       mwIndex i;
     
       if (nrhs != 1 || ! mxIsCell (prhs[0]))
         mexErrMsgTxt ("ARG1 must be a cell");
     
       n = mxGetNumberOfElements (prhs[0]);
       n = (n > nlhs ? nlhs : n);
     
       for (i = 0; i < n; i++)
         plhs[i] = mxDuplicateArray (mxGetCell (prhs[0], i));
     }

The output is identical to the oct-file version as well.

     [b1, b2, b3] = mycell ({1, [1, 2], "test"})
     ⇒
     b1 =  1
     b2 =

        1   2

     b3 = test

   Note in the example the use of the ‘mxDuplicateArray’ function.  This
is needed as the ‘mxArray’ pointer returned by ‘mxGetCell’ might be
deallocated.  The inverse function to ‘mxGetCell’, used for setting Cell
values, is ‘mxSetCell’ and is defined as

     void mxSetCell (mxArray *ptr, int idx, mxArray *val);

   Finally, to create a cell array or matrix, the appropriate functions
are

     mxArray *mxCreateCellArray (int ndims, const int *dims);
     mxArray *mxCreateCellMatrix (int m, int n);


File: octave.info,  Node: Structures with Mex-Files,  Next: Sparse Matrices with Mex-Files,  Prev: Cell Arrays with Mex-Files,  Up: Mex-Files

A.2.5 Structures with Mex-Files
-------------------------------

The basic function to create a structure in a mex-file is
‘mxCreateStructMatrix’ which creates a structure array with a two
dimensional matrix, or ‘mxCreateStructArray’.

     mxArray *mxCreateStructArray (int ndims, int *dims,
                                   int num_keys,
                                   const char **keys);
     mxArray *mxCreateStructMatrix (int rows, int cols,
                                    int num_keys,
                                    const char **keys);

   Accessing the fields of the structure can then be performed with
‘mxGetField’ and ‘mxSetField’ or alternatively with the
‘mxGetFieldByNumber’ and ‘mxSetFieldByNumber’ functions.

     mxArray *mxGetField (const mxArray *ptr, mwIndex index,
                          const char *key);
     mxArray *mxGetFieldByNumber (const mxArray *ptr,
                                  mwIndex index, int key_num);
     void mxSetField (mxArray *ptr, mwIndex index,
                      const char *key, mxArray *val);
     void mxSetFieldByNumber (mxArray *ptr, mwIndex index,
                              int key_num, mxArray *val);

   A difference between the oct-file interface to structures and the
mex-file version is that the functions to operate on structures in
mex-files directly include an ‘index’ over the elements of the arrays of
elements per ‘field’; Whereas, the oct-file structure includes a Cell
Array per field of the structure.

   An example that demonstrates the use of structures in a mex-file can
be found in the file ‘mystruct.c’ shown below.

     #include "mex.h"
     
     void
     mexFunction (int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
     {
       int i;
       mwIndex j;
       mxArray *v;
       const char *keys[] = { "this", "that" };
     
       if (nrhs != 1 || ! mxIsStruct (prhs[0]))
         mexErrMsgTxt ("ARG1 must be a struct");
     
       for (i = 0; i < mxGetNumberOfFields (prhs[0]); i++)
         for (j = 0; j < mxGetNumberOfElements (prhs[0]); j++)
           {
             mexPrintf ("field %s(%d) = ", mxGetFieldNameByNumber (prhs[0], i), j);
             v = mxGetFieldByNumber (prhs[0], j, i);
             mexCallMATLAB (0, NULL, 1, &v, "disp");
           }
     
       v = mxCreateStructMatrix (2, 2, 2, keys);
     
       mxSetFieldByNumber (v, 0, 0, mxCreateString ("this1"));
       mxSetFieldByNumber (v, 0, 1, mxCreateString ("that1"));
       mxSetFieldByNumber (v, 1, 0, mxCreateString ("this2"));
       mxSetFieldByNumber (v, 1, 1, mxCreateString ("that2"));
       mxSetFieldByNumber (v, 2, 0, mxCreateString ("this3"));
       mxSetFieldByNumber (v, 2, 1, mxCreateString ("that3"));
       mxSetFieldByNumber (v, 3, 0, mxCreateString ("this4"));
       mxSetFieldByNumber (v, 3, 1, mxCreateString ("that4"));
     
       if (nlhs)
         plhs[0] = v;
     }

   An example of the behavior of this function within Octave is then

     a(1).f1 = "f11"; a(1).f2 = "f12";
     a(2).f1 = "f21"; a(2).f2 = "f22";
     b = mystruct (a);
     ⇒  field f1(0) = f11
         field f1(1) = f21
         field f2(0) = f12
         field f2(1) = f22
     b
     ⇒ 2x2 struct array containing the fields:

          this
          that

     b(3)
     ⇒ scalar structure containing the fields:

          this = this3
          that = that3


File: octave.info,  Node: Sparse Matrices with Mex-Files,  Next: Calling Other Functions in Mex-Files,  Prev: Structures with Mex-Files,  Up: Mex-Files

A.2.6 Sparse Matrices with Mex-Files
------------------------------------

The Octave format for sparse matrices is identical to the mex format in
that it is a compressed column sparse format.  Also, in both
implementations sparse matrices are required to be two-dimensional.  The
only difference of importance to the programmer is that the real and
imaginary parts of the matrix are stored separately.

   The mex-file interface, in addition to using ‘mxGetM’, ‘mxGetN’,
‘mxSetM’, ‘mxSetN’, ‘mxGetPr’, ‘mxGetPi’, ‘mxSetPr’, and ‘mxSetPi’, also
supplies the following functions.

     mwIndex *mxGetIr (const mxArray *ptr);
     mwIndex *mxGetJc (const mxArray *ptr);
     mwSize mxGetNzmax (const mxArray *ptr);

     void mxSetIr (mxArray *ptr, mwIndex *ir);
     void mxSetJc (mxArray *ptr, mwIndex *jc);
     void mxSetNzmax (mxArray *ptr, mwSize nzmax);

‘mxGetNzmax’ gets the maximum number of elements that can be stored in
the sparse matrix.  This is not necessarily the number of nonzero
elements in the sparse matrix.  ‘mxGetJc’ returns an array with one
additional value than the number of columns in the sparse matrix.  The
difference between consecutive values of the array returned by ‘mxGetJc’
define the number of nonzero elements in each column of the sparse
matrix.  Therefore,

     mwSize nz, n;
     mwIndex *Jc;
     mxArray *m;
     ...
     n = mxGetN (m);
     Jc = mxGetJc (m);
     nz = Jc[n];

returns the actual number of nonzero elements stored in the matrix in
‘nz’.  As the arrays returned by ‘mxGetPr’ and ‘mxGetPi’ only contain
the nonzero values of the matrix, we also need a pointer to the rows of
the nonzero elements, and this is given by ‘mxGetIr’.  A complete
example of the use of sparse matrices in mex-files is given by the file
‘mysparse.c’ shown below.

     #include "mex.h"
     
     void
     mexFunction (int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
     {
       mwSize m, n, nz;
       mxArray *v;
       mwIndex i;
       double *pr, *pi;
       double *pr2, *pi2;
       mwIndex *ir, *jc;
       mwIndex *ir2, *jc2;
     
       if (nrhs != 1 || ! mxIsSparse (prhs[0]))
         mexErrMsgTxt ("ARG1 must be a sparse matrix");
     
       m = mxGetM (prhs[0]);
       n = mxGetN (prhs[0]);
       nz = mxGetNzmax (prhs[0]);
     
       if (mxIsComplex (prhs[0]))
         {
           mexPrintf ("Matrix is %d-by-%d complex sparse matrix", m, n);
           mexPrintf (" with %d elements\n", nz);
     
           pr = mxGetPr (prhs[0]);
           pi = mxGetPi (prhs[0]);
           ir = mxGetIr (prhs[0]);
           jc = mxGetJc (prhs[0]);
     
           i = n;
           while (jc[i] == jc[i-1] && i != 0) i--;
     
           mexPrintf ("last nonzero element (%d, %d) = (%g, %g)\n",
                      ir[nz-1]+ 1, i, pr[nz-1], pi[nz-1]);
     
           v = mxCreateSparse (m, n, nz, mxCOMPLEX);
           pr2 = mxGetPr (v);
           pi2 = mxGetPi (v);
           ir2 = mxGetIr (v);
           jc2 = mxGetJc (v);
     
           for (i = 0; i < nz; i++)
             {
               pr2[i] = 2 * pr[i];
               pi2[i] = 2 * pi[i];
               ir2[i] = ir[i];
             }
           for (i = 0; i < n + 1; i++)
             jc2[i] = jc[i];
     
           if (nlhs > 0)
             plhs[0] = v;
         }
       else if (mxIsLogical (prhs[0]))
         {
           mxLogical *pbr, *pbr2;
           mexPrintf ("Matrix is %d-by-%d logical sparse matrix", m, n);
           mexPrintf (" with %d elements\n", nz);
     
           pbr = mxGetLogicals (prhs[0]);
           ir = mxGetIr (prhs[0]);
           jc = mxGetJc (prhs[0]);
     
           i = n;
           while (jc[i] == jc[i-1] && i != 0) i--;
           mexPrintf ("last nonzero element (%d, %d) = %d\n",
                      ir[nz-1]+ 1, i, pbr[nz-1]);
     
           v = mxCreateSparseLogicalMatrix (m, n, nz);
           pbr2 = mxGetLogicals (v);
           ir2 = mxGetIr (v);
           jc2 = mxGetJc (v);
     
           for (i = 0; i < nz; i++)
             {
               pbr2[i] = pbr[i];
               ir2[i] = ir[i];
             }
           for (i = 0; i < n + 1; i++)
             jc2[i] = jc[i];
     
           if (nlhs > 0)
             plhs[0] = v;
         }
       else
         {
           mexPrintf ("Matrix is %d-by-%d real sparse matrix", m, n);
           mexPrintf (" with %d elements\n", nz);
     
           pr = mxGetPr (prhs[0]);
           ir = mxGetIr (prhs[0]);
           jc = mxGetJc (prhs[0]);
     
           i = n;
           while (jc[i] == jc[i-1] && i != 0) i--;
           mexPrintf ("last nonzero element (%d, %d) = %g\n",
                      ir[nz-1]+ 1, i, pr[nz-1]);
     
           v = mxCreateSparse (m, n, nz, mxREAL);
           pr2 = mxGetPr (v);
           ir2 = mxGetIr (v);
           jc2 = mxGetJc (v);
     
           for (i = 0; i < nz; i++)
             {
               pr2[i] = 2 * pr[i];
               ir2[i] = ir[i];
             }
           for (i = 0; i < n + 1; i++)
             jc2[i] = jc[i];
     
           if (nlhs > 0)
             plhs[0] = v;
         }
     }

   A sample usage of ‘mysparse’ is

     sm = sparse ([1, 0; 0, pi]);
     mysparse (sm)
     ⇒
     Matrix is 2-by-2 real sparse matrix with 2 elements
     last nonzero element (2, 2) = 3.14159


File: octave.info,  Node: Calling Other Functions in Mex-Files,  Prev: Sparse Matrices with Mex-Files,  Up: Mex-Files

A.2.7 Calling Other Functions in Mex-Files
------------------------------------------

It is possible to call other Octave functions from within a mex-file
using ‘mexCallMATLAB’.  An example of the use of ‘mexCallMATLAB’ can be
see in the example below.

     #include "mex.h"
     
     void
     mexFunction (int nlhs, mxArray *plhs[],
                  int nrhs, const mxArray *prhs[])
     {
       char *str;
     
       mexPrintf ("Starting file myfeval.mex\n");
     
       mexPrintf ("I have %d inputs and %d outputs\n", nrhs, nlhs);
     
       if (nrhs < 1 || ! mxIsChar (prhs[0]))
         mexErrMsgTxt ("ARG1 must be a function name");
     
       str = mxArrayToString (prhs[0]);
     
       mexPrintf ("I'm going to call the function %s\n", str);
     
       if (nlhs == 0)
         nlhs = 1;  // Octave's automatic 'ans' variable
     
       /* Cast prhs just to get rid of 'const' qualifier and stop compile warning */
       mexCallMATLAB (nlhs, plhs, nrhs-1, (mxArray**)prhs+1, str);
     
       mxFree (str);
     }

   If this code is in the file ‘myfeval.c’, and is compiled to
‘myfeval.mex’, then an example of its use is

     a = myfeval ("sin", 1)
     ⇒ Starting file myfeval.mex
        I have 2 inputs and 1 outputs
        I'm going to call the interpreter function sin
        a =  0.84147

   Note that it is not possible to use function handles within a
mex-file.


File: octave.info,  Node: Standalone Programs,  Next: Java Interface,  Prev: Mex-Files,  Up: External Code Interface

A.3 Standalone Programs
=======================

The libraries Octave uses itself can be utilized in standalone
applications.  These applications then have access, for example, to the
array and matrix classes, as well as to all of the Octave algorithms.
The following C++ program, uses class Matrix from ‘liboctave.a’ or
‘liboctave.so’.

     #include <iostream>
     #include <octave/oct.h>
     
     int
     main (void)
     {
       std::cout << "Hello Octave world!\n";
     
       int n = 2;
       Matrix a_matrix = Matrix (n, n);
     
       for (octave_idx_type i = 0; i < n; i++)
         for (octave_idx_type j = 0; j < n; j++)
           a_matrix(i,j) = (i + 1) * 10 + (j + 1);
     
       std::cout << a_matrix;
     
       return 0;
     }

mkoctfile can be used to build a standalone application with a command
like

     $ mkoctfile --link-stand-alone standalone.cc -o standalone
     $ ./standalone
     Hello Octave world!
       11 12
       21 22
     $

   Note that the application ‘standalone’ will be dynamically linked
against the Octave libraries and any Octave support libraries.  The
above allows the Octave math libraries to be used by an application.  It
does not, however, allow the script files, oct-files, or built-in
functions of Octave to be used by the application.  To do that, the
Octave interpreter needs to be initialized first.  An example of how to
do this can then be seen in the code

     #include <iostream>
     #include <octave/oct.h>
     #include <octave/octave.h>
     #include <octave/parse.h>
     #include <octave/interpreter.h>
     
     int
     main (void)
     {
       // Create interpreter.
     
       octave::interpreter interpreter;
     
       try
         {
           // Inhibit reading history file by calling
           //
           //   interpreter.initialize_history (false);
     
           // Set custom load path here if you wish by calling
           //
           //   interpreter.initialize_load_path (false);
     
           // Perform final initialization of interpreter, including
           // executing commands from startup files by calling
           //
           //   interpreter.initialize ();
           //
           //   if (! interpreter.initialized ())
           //     {
           //       std::cerr << "Octave interpreter initialization failed!"
           //                 << std::endl;
           //       exit (status);
           //     }
           //
           // You may skip this step if you don't need to do anything
           // between reading the startup files and telling the interpreter
           // that you are ready to execute commands.
     
           // Tell the interpreter that we're ready to execute commands:
     
           int status = interpreter.execute ();
     
           if (status != 0)
             {
               std::cerr << "creating embedded Octave interpreter failed!"
                         << std::endl;
               return status;
             }
     
           octave_idx_type n = 2;
           octave_value_list in;
     
           for (octave_idx_type i = 0; i < n; i++)
             in(i) = octave_value (5 * (i + 2));
     
           octave_value_list out = octave::feval ("gcd", in, 1);
     
           if (out.length () > 0)
             std::cout << "GCD of ["
                       << in(0).int_value ()
                       << ", "
                       << in(1).int_value ()
                       << "] is " << out(0).int_value ()
                       << std::endl;
           else
             std::cout << "invalid\n";
         }
       catch (const octave::exit_exception& ex)
         {
           std::cerr << "Octave interpreter exited with status = "
                     << ex.exit_status () << std::endl;
         }
       catch (const octave::execution_exception&)
         {
           std::cerr << "error encountered in Octave evaluator!" << std::endl;
         }
     
       return 0;
     }

which, as before, is compiled and run as a standalone application with

     $ mkoctfile --link-stand-alone embedded.cc -o embedded
     $ ./embedded
     GCD of [10, 15] is 5
     $

   It is worth re-iterating that, if only built-in functions are to be
called from a C++ standalone program then it does not need to initialize
the interpreter.  The general rule is that for a built-in function named
‘function_name’ in the interpreter, there will be a C++ function named
‘Ffunction_name’ (note the prepended capital ‘F’) accessible in the C++
API.  The declarations for all built-in functions are collected in the
header file ‘builtin-defun-decls.h’.  This feature should be used with
care as the list of built-in functions can change.  No guarantees can be
made that a function that is currently a built-in won’t be implemented
as a ‘.m’ file or as a dynamically linked function in the future.  An
example of how to call built-in functions from C++ can be seen in the
code

     #include <iostream>
     #include <octave/oct.h>
     #include <octave/builtin-defun-decls.h>
     
     int
     main (void)
     {
       int n = 2;
       Matrix a_matrix = Matrix (n, n);
     
       for (octave_idx_type i = 0; i < n; i++)
         for (octave_idx_type j = 0; j < n; j++)
           a_matrix(i,j) = (i + 1) * 10 + (j + 1);
     
       std::cout << "This is a matrix:" << std::endl
                 << a_matrix            << std::endl;
     
       octave_value_list in;
       in(0) = a_matrix;
     
       octave_value_list out = Fnorm (in, 1);
       double norm_of_the_matrix = out(0).double_value ();
     
       std::cout << "This is the norm of the matrix:" << std::endl
                 << norm_of_the_matrix                << std::endl;
     
       return 0;
     }

which is compiled and run as a standalone application with

     $ mkoctfile --link-stand-alone standalonebuiltin.cc -o standalonebuiltin
     $ ./standalonebuiltin
     This is a matrix:
      11 12
      21 22

     This is the norm of the matrix:
     34.4952
     $


File: octave.info,  Node: Java Interface,  Prev: Standalone Programs,  Up: External Code Interface

A.4 Java Interface
==================

The Java Interface is designed for calling Java functions from within
Octave.  If you want to do the reverse, and call Octave from within
Java, try a library like ‘joPas’ (<http://jopas.sourceforge.net>).

* Menu:

* Making Java Classes Available::
* How to use Java from within Octave::
* Set up the JVM::
* Java Interface Functions::


File: octave.info,  Node: Making Java Classes Available,  Next: How to use Java from within Octave,  Up: Java Interface

A.4.1 Making Java Classes Available
-----------------------------------

Java finds classes by searching a CLASSPATH which is a list of Java
archive files and/or directories containing class files.  In Octave the
CLASSPATH is composed of two parts:

   • the STATIC CLASSPATH is initialized once at startup of the JVM, and

   • the DYNAMIC CLASSPATH which can be modified at runtime.

   Octave searches the STATIC CLASSPATH first, and then the DYNAMIC
CLASSPATH.  Classes appearing in the STATIC CLASSPATH, as well as in the
DYNAMIC CLASSPATH, will therefore be found in the STATIC CLASSPATH and
loaded from this location.  Classes which will be used frequently, or
must be available to all users, should be added to the STATIC CLASSPATH.
The STATIC CLASSPATH is populated once from the contents of a plain text
file named ‘javaclasspath.txt’ (or ‘classpath.txt’ historically) when
the Java Virtual Machine starts.  This file contains one line for each
individual classpath to be added to the STATIC CLASSPATH.  These lines
can identify directories containing class files, or Java archives with
complete class file hierarchies.  Comment lines starting with a ‘#’ or a
‘%’ character are ignored.

   The search rules for the file ‘javaclasspath.txt’ (or
‘classpath.txt’) are:

   • First, Octave tries to locate it in the current directory (where
     Octave was started from).  If such a file is found, it is read and
     defines the initial STATIC CLASSPATH.  Thus, it is possible to
     define a static classpath on a ’per Octave invocation’ basis.

   • Next, Octave searches in the user’s home directory.  If a file
     ‘javaclasspath.txt’ exists here, its contents are appended to the
     static classpath (if any).  Thus, it is possible to build an
     initial static classpath on a ’per user’ basis.

   • Finally, Octave looks for a ‘javaclasspath.txt’ in the m-file
     directory where Octave Java functions live.  This is where the
     function ‘javaclasspath.m’ resides, usually something like
     ‘OCTAVE_HOME/share/octave/OCTAVE_VERSION/m/java/’.  You can find
     this directory by executing the command

          which javaclasspath

     If this file exists here, its contents are also appended to the
     STATIC CLASSPATH.  Note that the archives and class directories
     defined in this last step will affect all users.

   Classes which are used only by a specific script should be placed in
the DYNAMIC CLASSPATH.  This portion of the classpath can be modified at
runtime using the ‘javaaddpath’ and ‘javarmpath’ functions.

   Example:

     octave> base_path = "C:/Octave/java_files";

     octave> # add two JAR archives to the dynamic classpath
     octave> javaaddpath ([base_path, "/someclasses.jar"]);
     octave> javaaddpath ([base_path, "/moreclasses.jar"]);

     octave> # check the dynamic classpath
     octave> p = javaclasspath;
     octave> disp (p{1});
     C:/Octave/java_files/someclasses.jar
     octave> disp (p{2});
     C:/Octave/java_files/moreclasses.jar

     octave> # remove the first element from the classpath
     octave> javarmpath ([base_path, "/someclasses.jar"]);
     octave> p = javaclasspath;
     octave> disp (p{1});
     C:/Octave/java_files/moreclasses.jar

     octave> # provoke an error
     octave> disp (p{2});
     error: A(I): Index exceeds matrix dimension.

   Another way to add files to the DYNAMIC CLASSPATH exclusively for
your user account is to use the file ‘.octaverc’ which is stored in your
home directory.  All Octave commands in this file are executed each time
you start a new instance of Octave.  The following example adds the
directory ‘octave’ to Octave’s search path and the archive
‘myclasses.jar’ in this directory to the Java search path.

     # contents of .octaverc:
     addpath ("~/octave");
     javaaddpath ("~/octave/myclasses.jar");


File: octave.info,  Node: How to use Java from within Octave,  Next: Set up the JVM,  Prev: Making Java Classes Available,  Up: Java Interface

A.4.2 How to use Java from within Octave
----------------------------------------

The function *note javaObject: XREFjavaObject. creates Java objects.  In
fact it invokes the public constructor of the class with the given name
and with the given parameters.

   The following example shows how to invoke the constructors
‘BigDecimal(double)’ and ‘BigDecimal(String)’ of the builtin Java class
‘java.math.BigDecimal’.

     javaObject ("java.math.BigDecimal",  1.001 );
     javaObject ("java.math.BigDecimal", "1.001");

   Note that parameters of the Octave type ‘double’ are implicitly
converted into the Java type ‘double’ and the Octave type (array of)
‘char’ is converted into the java type ‘String’.  A Java object created
by *note javaObject: XREFjavaObject. is never automatically converted
into an Octave type but remains a Java object.  It can be assigned to an
Octave variable.

     a = 1.001;
     b = javaObject ("java.math.BigDecimal", a);

   Using *note isjava: XREFisjava, it is possible to check whether a
variable is a Java object and its class can be determined as well.  In
addition to the previous example:

     isjava (a)
     ⇒ ans = 0
     class (a)
     ⇒ ans = double
     isjava (b)
     ⇒ ans = 1
     class (b)
     ⇒ ans = java.math.BigDecimal

   The example above can be carried out using only Java objects:

     a = javaObject ("java.lang.Double", 1.001);
     b = javaObject ("java.math.BigDecimal", a);

     isjava (a)
     ⇒ ans = 1
     class (a)
     ⇒ ans = java.lang.Double
     isjava (b)
     ⇒ ans = 1
     class (b)
     ⇒ ans = java.math.BigDecimal

   One can see, that even a ‘java.lang.Double’ is not converted to an
Octave ‘double’, when created by *note javaObject: XREFjavaObject.  But
ambiguities might arise, if the Java classes ‘java.lang.Double’ or
‘double’ are parameters of a method (or a constructor).  In this case
they can be converted into one another, depending on the context.

   Via *note javaObject: XREFjavaObject. one may create all kinds of
Java objects but arrays.  The latter are created through *note
javaArray: XREFjavaArray.

   It is possible to invoke public member methods on Java objects in
Java syntax:

     a.toString
     ⇒ ans = 1.001
     b.toString
     ⇒ ans = 1.000999999999999889865...

   The second result may be surprising, but simply comes from the fact,
that ‘1.001’ cannot exactly be represented as ‘double’, due to rounding.
Note that unlike in Java, in Octave methods without arguments can be
invoked with and without parentheses ‘()’.

   Currently it is not possible to invoke static methods with a Java
like syntax from within Octave.  Instead, one has to use the function
*note javaMethod: XREFjavaMethod. as in the following example:

     java.math.BigDecimal.valueOf(1.001);                    # does not work
     javaMethod ("valueOf", "java.math.BigDecimal", 1.001);  # workaround

   As mentioned before, method and constructor parameters are converted
automatically between Octave and Java types, if appropriate.  For
functions this is also true with return values, whereas for constructors
this is not.

   It is also possible to access public fields of Java objects from
within Octave using Java syntax, with the limitation of static fields:

     java.math.BigDecimal.ONE;                  # does not work
     java_get ("java.math.BigDecimal", "ONE");  # workaround

   Accordingly, with *note java_set: XREFjava_set. the value of a field
can be set.  Note that only public Java fields are accessible from
within Octave.

   The following example indicates that in Octave empty brackets ‘[]’
represent Java’s ‘null’ value and how Java exceptions are represented.

     javaObject ("java.math.BigDecimal", []);
     ⇒ error: [java] java.lang.NullPointerException

   It is not recommended to represent Java’s ‘null’ value by empty
brackets ‘[]’, because ‘null’ has no type whereas ‘[]’ has type
‘double’.

   In Octave it is possible to provide limited Java reflection by
listing the public fields and methods of a Java object, both static or
not.

     fieldnames (<Java object>)
     methods (<Java object>)

   Finally, an examples is shown how to access the stack trace from
within Octave, where the function *note debug_java: XREFdebug_java. is
used to set and to get the current debug state.  In debug mode, the Java
error and the stack trace are displayed.

     debug_java (true)  # use "false" to omit display of stack trace
     debug_java ()
     ⇒ ans = 1
     javaObject ("java.math.BigDecimal", "1") ...
       .divide (javaObject ("java.math.BigDecimal", "0"))

