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

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

Copyright © 1996-2018 John W. Eaton.

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

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

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


File: octave.info,  Node: Global Variables,  Next: Persistent Variables,  Up: Variables

7.1 Global Variables
====================

A variable that has been declared “global” may be accessed from within a
function body without having to pass it as a formal parameter.

   A variable may be declared global using a ‘global’ declaration
statement.  The following statements are all global declarations.

     global a
     global a b
     global c = 2
     global d = 3 e f = 5

   A global variable may only be initialized once in a ‘global’
statement.  For example, after executing the following code

     global gvar = 1
     global gvar = 2

the value of the global variable ‘gvar’ is 1, not 2.  Issuing a ‘clear
gvar’ command does not change the above behavior, but ‘clear all’ does.

   It is necessary declare a variable as global within a function body
in order to access it.  For example,

     global x
     function f ()
       x = 1;
     endfunction
     f ()

does _not_ set the value of the global variable ‘x’ to 1.  In order to
change the value of the global variable ‘x’, you must also declare it to
be global within the function body, like this

     function f ()
       global x;
       x = 1;
     endfunction

   Passing a global variable in a function parameter list will make a
local copy and not modify the global value.  For example, given the
function

     function f (x)
       x = 0
     endfunction

and the definition of ‘x’ as a global variable at the top level,

     global x = 13

the expression

     f (x)

will display the value of ‘x’ from inside the function as 0, but the
value of ‘x’ at the top level remains unchanged, because the function
works with a _copy_ of its argument.

 -- : isglobal (NAME)
     Return true if NAME is a globally visible variable.

     For example:

          global x
          isglobal ("x")
             ⇒ 1

     See also: *note isvarname: XREFisvarname, *note exist: XREFexist.


File: octave.info,  Node: Persistent Variables,  Next: Status of Variables,  Prev: Global Variables,  Up: Variables

7.2 Persistent Variables
========================

A variable that has been declared “persistent” within a function will
retain its contents in memory between subsequent calls to the same
function.  The difference between persistent variables and global
variables is that persistent variables are local in scope to a
particular function and are not visible elsewhere.

   The following example uses a persistent variable to create a function
that prints the number of times it has been called.

     function count_calls ()
       persistent calls = 0;
       printf ("'count_calls' has been called %d times\n",
               ++calls);
     endfunction

     for i = 1:3
       count_calls ();
     endfor

     ⊣ 'count_calls' has been called 1 times
     ⊣ 'count_calls' has been called 2 times
     ⊣ 'count_calls' has been called 3 times

   As the example shows, a variable may be declared persistent using a
‘persistent’ declaration statement.  The following statements are all
persistent declarations.

     persistent a
     persistent a b
     persistent c = 2
     persistent d = 3 e f = 5

   The behavior of persistent variables is equivalent to the behavior of
static variables in C.

   One restriction for persistent variables is, that neither input nor
output arguments of a function can be persistent:

     function y = foo ()
       persistent y = 0;  # Not allowed!
     endfunction

     foo ()
     ⊣ error: can't make function parameter y persistent

   Like global variables, a persistent variable may only be initialized
once.  For example, after executing the following code

     persistent pvar = 1
     persistent pvar = 2

the value of the persistent variable ‘pvar’ is 1, not 2.

   If a persistent variable is declared but not initialized to a
specific value, it will contain an empty matrix.  So, it is also
possible to initialize a persistent variable by checking whether it is
empty, as the following example illustrates.

     function count_calls ()
       persistent calls;
       if (isempty (calls))
         calls = 0;
       endif
       printf ("'count_calls' has been called %d times\n",
               ++calls);
     endfunction

This implementation behaves in exactly the same way as the previous
implementation of ‘count_calls’.

   The value of a persistent variable is kept in memory until it is
explicitly cleared.  Assuming that the implementation of ‘count_calls’
is saved on disk, we get the following behavior.

     for i = 1:2
       count_calls ();
     endfor
     ⊣ 'count_calls' has been called 1 times
     ⊣ 'count_calls' has been called 2 times

     clear
     for i = 1:2
       count_calls ();
     endfor
     ⊣ 'count_calls' has been called 3 times
     ⊣ 'count_calls' has been called 4 times

     clear all
     for i = 1:2
       count_calls ();
     endfor
     ⊣ 'count_calls' has been called 1 times
     ⊣ 'count_calls' has been called 2 times

     clear count_calls
     for i = 1:2
       count_calls ();
     endfor
     ⊣ 'count_calls' has been called 1 times
     ⊣ 'count_calls' has been called 2 times

That is, the persistent variable is only removed from memory when the
function containing the variable is removed.  Note that if the function
definition is typed directly into the Octave prompt, the persistent
variable will be cleared by a simple ‘clear’ command as the entire
function definition will be removed from memory.  If you do not want a
persistent variable to be removed from memory even if the function is
cleared, you should use the ‘mlock’ function (*note Function Locking::).


File: octave.info,  Node: Status of Variables,  Prev: Persistent Variables,  Up: Variables

7.3 Status of Variables
=======================

When creating simple one-shot programs it can be very convenient to see
which variables are available at the prompt.  The function ‘who’ and its
siblings ‘whos’ and ‘whos_line_format’ will show different information
about what is in memory, as the following shows.

     str = "A random string";
     who
      ⊣ Variables in the current scope:
      ⊣
      ⊣ ans  str

 -- : who
 -- : who pattern ...
 -- : who option pattern ...
 -- : C = who ("pattern", ...)
     List currently defined variables matching the given patterns.

     Valid pattern syntax is the same as described for the ‘clear’
     command.  If no patterns are supplied, all variables are listed.

     By default, only variables visible in the local scope are
     displayed.

     The following are valid options, but may not be combined.

     ‘global’
          List variables in the global scope rather than the current
          scope.

     ‘-regexp’
          The patterns are considered to be regular expressions when
          matching the variables to display.  The same pattern syntax
          accepted by the ‘regexp’ function is used.

     ‘-file’
          The next argument is treated as a filename.  All variables
          found within the specified file are listed.  No patterns are
          accepted when reading variables from a file.

     If called as a function, return a cell array of defined variable
     names matching the given patterns.

     See also: *note whos: XREFwhos, *note isglobal: XREFisglobal, *note
     isvarname: XREFisvarname, *note exist: XREFexist, *note regexp:
     XREFregexp.

 -- : whos
 -- : whos pattern ...
 -- : whos option pattern ...
 -- : S = whos ("pattern", ...)
     Provide detailed information on currently defined variables
     matching the given patterns.

     Options and pattern syntax are the same as for the ‘who’ command.

     Extended information about each variable is summarized in a table
     with the following default entries.

     Attr
          Attributes of the listed variable.  Possible attributes are:

          blank
               Variable in local scope

          ‘a’
               Automatic variable.  An automatic variable is one created
               by the interpreter, for example ‘argn’.

          ‘c’
               Variable of complex type.

          ‘f’
               Formal parameter (function argument).

          ‘g’
               Variable with global scope.

          ‘p’
               Persistent variable.

     Name
          The name of the variable.

     Size
          The logical size of the variable.  A scalar is 1x1, a vector
          is 1xN or Nx1, a 2-D matrix is MxN.

     Bytes
          The amount of memory currently used to store the variable.

     Class
          The class of the variable.  Examples include double, single,
          char, uint16, cell, and struct.

     The table can be customized to display more or less information
     through the function ‘whos_line_format’.

     If ‘whos’ is called as a function, return a struct array of defined
     variable names matching the given patterns.  Fields in the
     structure describing each variable are: name, size, bytes, class,
     global, sparse, complex, nesting, persistent.

     See also: *note who: XREFwho, *note whos_line_format:
     XREFwhos_line_format.

 -- : VAL = whos_line_format ()
 -- : OLD_VAL = whos_line_format (NEW_VAL)
 -- : whos_line_format (NEW_VAL, "local")
     Query or set the format string used by the command ‘whos’.

     A full format string is:

          %[modifier]<command>[:width[:left-min[:balance]]];

     The following command sequences are available:

     ‘%a’
          Prints attributes of variables (g=global, p=persistent,
          f=formal parameter, a=automatic variable).

     ‘%b’
          Prints number of bytes occupied by variables.

     ‘%c’
          Prints class names of variables.

     ‘%e’
          Prints elements held by variables.

     ‘%n’
          Prints variable names.

     ‘%s’
          Prints dimensions of variables.

     ‘%t’
          Prints type names of variables.

     Every command may also have an alignment modifier:

     ‘l’
          Left alignment.

     ‘r’
          Right alignment (default).

     ‘c’
          Column-aligned (only applicable to command %s).

     The ‘width’ parameter is a positive integer specifying the minimum
     number of columns used for printing.  No maximum is needed as the
     field will auto-expand as required.

     The parameters ‘left-min’ and ‘balance’ are only available when the
     column-aligned modifier is used with the command ‘%s’.  ‘balance’
     specifies the column number within the field width which will be
     aligned between entries.  Numbering starts from 0 which indicates
     the leftmost column.  ‘left-min’ specifies the minimum field width
     to the left of the specified balance column.

     The default format is:

     " %a:4; %ln:6; %cs:16:6:1; %rb:12; %lc:-1;\n"

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

   Instead of displaying which variables are in memory, it is possible
to determine if a given variable is available.  That way it is possible
to alter the behavior of a program depending on the existence of a
variable.  The following example illustrates this.

     if (! exist ("meaning", "var"))
       disp ("The program has no 'meaning'");
     endif

 -- : C = exist (NAME)
 -- : C = exist (NAME, TYPE)
     Check for the existence of NAME as a variable, function, file,
     directory, or class.

     The return code C is one of

     1
          NAME is a variable.

     2
          NAME is an absolute filename, an ordinary file in Octave’s
          ‘path’, or (after appending ‘.m’) a function file in Octave’s
          ‘path’.

     3
          NAME is a ‘.oct’ or ‘.mex’ file in Octave’s ‘path’.

     5
          NAME is a built-in function.

     7
          NAME is a directory.

     8
          NAME is a class.  (Note: not currently implemented)

     103
          NAME is a function not associated with a file (entered on the
          command line).

     0
          NAME does not exist.

     If the optional argument TYPE is supplied, check only for symbols
     of the specified type.  Valid types are

     "var"
          Check only for variables.

     "builtin"
          Check only for built-in functions.

     "dir"
          Check only for directories.

     "file"
          Check only for files and directories.

     "class"
          Check only for classes.  (Note: This option is accepted, but
          not currently implemented)

     If no type is given, and there are multiple possible matches for
     name, ‘exist’ will return a code according to the following
     priority list: variable, built-in function, oct-file, directory,
     file, class.

     ‘exist’ returns 2 if a regular file called NAME is present in
     Octave’s search path.  For information about other types of files
     not on the search path use some combination of the functions
     ‘file_in_path’ and ‘stat’ instead.

     Programming Note: If NAME is implemented by a buggy .oct/.mex file,
     calling EXIST may cause Octave to crash.  To maintain high
     performance, Octave trusts .oct/.mex files instead of sandboxing
     them.

     See also: *note file_in_loadpath: XREFfile_in_loadpath, *note
     file_in_path: XREFfile_in_path, *note dir_in_loadpath:
     XREFdir_in_loadpath, *note stat: XREFstat.

   Usually Octave will manage the memory, but sometimes it can be
practical to remove variables from memory manually.  This is usually
needed when working with large variables that fill a substantial part of
the memory.  On a computer that uses the IEEE floating point format, the
following program allocates a matrix that requires around 128 MB memory.

     large_matrix = zeros (4000, 4000);

Since having this variable in memory might slow down other computations,
it can be necessary to remove it manually from memory.  The ‘clear’
function allows this.

 -- : clear [options] pattern ...
     Delete the names matching the given patterns from the symbol table.

     The pattern may contain the following special characters:

     ‘?’
          Match any single character.

     ‘*’
          Match zero or more characters.

     ‘[ LIST ]’
          Match the list of characters specified by LIST.  If the first
          character is ‘!’ or ‘^’, match all characters except those
          specified by LIST.  For example, the pattern ‘[a-zA-Z]’ will
          match all lowercase and uppercase alphabetic characters.

     For example, the command

          clear foo b*r

     clears the name ‘foo’ and all names that begin with the letter ‘b’
     and end with the letter ‘r’.

     If ‘clear’ is called without any arguments, all user-defined
     variables (local and global) are cleared from the symbol table.

     If ‘clear’ is called with at least one argument, only the visible
     names matching the arguments are cleared.  For example, suppose you
     have defined a function ‘foo’, and then hidden it by performing the
     assignment ‘foo = 2’.  Executing the command ‘clear foo’ once will
     clear the variable definition and restore the definition of ‘foo’
     as a function.  Executing ‘clear foo’ a second time will clear the
     function definition.

     The following options are available in both long and short form

     ‘-all, -a’
          Clear all local and global user-defined variables and all
          functions from the symbol table.

     ‘-exclusive, -x’
          Clear the variables that don’t match the following pattern.

     ‘-functions, -f’
          Clear the function names and the built-in symbols names.

     ‘-global, -g’
          Clear global symbol names.

     ‘-variables, -v’
          Clear local variable names.

     ‘-classes, -c’
          Clears the class structure table and clears all objects.

     ‘-regexp, -r’
          The arguments are treated as regular expressions as any
          variables that match will be cleared.

     With the exception of ‘exclusive’, all long options can be used
     without the dash as well.

     See also: *note who: XREFwho, *note whos: XREFwhos, *note exist:
     XREFexist.

 -- : pack ()
     Consolidate workspace memory in MATLAB.

     This function is provided for compatibility, but does nothing in
     Octave.

     See also: *note clear: XREFclear.

   Information about a function or variable such as its location in the
file system can also be acquired from within Octave.  This is usually
only useful during development of programs, and not within a program.

 -- : type NAME ...
 -- : type -q NAME ...
 -- : text = type ("NAME", ...)
     Display the contents of NAME which may be a file, function
     (m-file), variable, operator, or keyword.

     ‘type’ normally prepends a header line describing the category of
     NAME such as function or variable; The ‘-q’ option suppresses this
     behavior.

     If no output variable is used the contents are displayed on screen.
     Otherwise, a cell array of strings is returned, where each element
     corresponds to the contents of each requested function.

 -- : which name ...
     Display the type of each NAME.

     If NAME is defined from a function file, the full name of the file
     is also displayed.

     See also: *note help: XREFhelp, *note lookfor: XREFlookfor.

 -- : what
 -- : what DIR
 -- : w = what (DIR)
     List the Octave specific files in directory DIR.

     If DIR is not specified then the current directory is used.

     If a return argument is requested, the files found are returned in
     the structure W.  The structure contains the following fields:

     path
          Full path to directory DIR

     m
          Cell array of m-files

     mat
          Cell array of mat files

     mex
          Cell array of mex files

     oct
          Cell array of oct files

     mdl
          Cell array of mdl files

     slx
          Cell array of slx files

     p
          Cell array of p-files

     classes
          Cell array of class directories (‘@CLASSNAME/’)

     packages
          Cell array of package directories (‘+PKGNAME/’)

     Compatibility Note: Octave does not support mdl, slx, and p files;
     nor does it support package directories.  ‘what’ will always return
     an empty list for these categories.

     See also: *note which: XREFwhich, *note ls: XREFls, *note exist:
     XREFexist.


File: octave.info,  Node: Expressions,  Next: Evaluation,  Prev: Variables,  Up: Top

8 Expressions
*************

Expressions are the basic building block of statements in Octave.  An
expression evaluates to a value, which you can print, test, store in a
variable, pass to a function, or assign a new value to a variable with
an assignment operator.

   An expression can serve as a statement on its own.  Most other kinds
of statements contain one or more expressions which specify data to be
operated on.  As in other languages, expressions in Octave include
variables, array references, constants, and function calls, as well as
combinations of these with various operators.

* Menu:

* Index Expressions::
* Calling Functions::
* Arithmetic Ops::
* Comparison Ops::
* Boolean Expressions::
* Assignment Ops::
* Increment Ops::
* Operator Precedence::


File: octave.info,  Node: Index Expressions,  Next: Calling Functions,  Up: Expressions

8.1 Index Expressions
=====================

An “index expression” allows you to reference or extract selected
elements of a vector, a matrix (2-D), or a higher-dimensional array.

   Indices may be scalars, vectors, ranges, or the special operator ‘:’,
which selects entire rows, columns, or higher-dimensional slices.

   An index expression consists of a set of parentheses enclosing M
expressions separated by commas.  Each individual index value, or
component, is used for the respective dimension of the object that it is
applied to.  In other words, the first index component is used for the
first dimension (rows) of the object, the second index component is used
for the second dimension (columns) of the object, and so on.  The number
of index components M defines the dimensionality of the index
expression.  An index with two components would be referred to as a 2-D
index because it has two dimensions.

   In the simplest case, 1) all components are scalars, and 2) the
dimensionality of the index expression M is equal to the dimensionality
of the object it is applied to.  For example:

     A = reshape (1:8, 2, 2, 2)  # Create 3-D array
     A =

     ans(:,:,1) =

        1   3
        2   4

     ans(:,:,2) =

        5   7
        6   8

     A(2, 1, 2)   # second row, first column of second slice
                  # in third dimension: ans = 6

   The size of the returned object in a specific dimension is equal to
the number of elements in the corresponding component of the index
expression.  When all components are scalars, the result is a single
output value.  However, if any component is a vector or range then the
returned values are the Cartesian product of the indices in the
respective dimensions.  For example:

     A([1, 2], 1, 2) ≡ [A(1,1,2); A(2,1,2)]
     ⇒
     ans =
        5
        6

   The total number of returned values is the product of the number of
elements returned for each index component.  In the example above, the
total is 2*1*1 = 2 elements.

   Notice that the size of the returned object in a given dimension is
equal to the number of elements in the index expression for that
dimension.  In the code above, the first index component (‘[1, 2]’) was
specified as a row vector, but its shape is unimportant.  The important
fact is that the component specified two values, and hence the result
must have a size of two in the first dimension; and because the first
dimension corresponds to rows, the overall result is a column vector.

     A(1, [2, 1, 1], 1)    # result is a row vector: ans = [3, 1, 1]
     A(ones (2, 2), 1, 1)  # result is a column vector: ans = [1; 1; 1; 1]

   The first line demonstrates again that the size of the output in a
given dimension is equal to the number of elements in the respective
indexing component.  In this case, the output has three elements in the
second dimension (which corresponds to columns), so the result is a row
vector.  The example also shows how repeating entries in the index
expression can be used to replicate elements in the output.  The last
example further proves that the shape of the indexing component is
irrelevant, it is only the number of elements (2x2 = 4) which is
important.

   The above rules apply whenever the dimensionality of the index
expression is greater than one (M > 1).  However, for one-dimensional
index expressions special rules apply and the shape of the output *is*
determined by the shape of the indexing component.  For example:

     A([1, 2])  # result is a row vector: ans = [1, 2]
     A([1; 2])  # result is a column vector: ans = [1; 2]

   Note that it is permissible to use a 1-D index with a
multi-dimensional object (also called linear indexing).  In this case,
the elements of the multi-dimensional array are taken in column-first
order like Fortran.  That is, the columns of the array are imagined to
be stacked on top of each other to form a column vector and then the
single linear index is applied to this vector.

     A(5)    # linear indexing into three-dimensional array: ans = 5
     A(3:5)  # result has shape of index component: ans = [3, 4, 5]

   A colon (‘:’) may be used as an index component to select all of the
elements in a specified dimension.  Given the matrix,

     A = [1, 2; 3, 4]

all of the following expressions are equivalent and select the first row
of the matrix.

     A(1, [1, 2])  # row 1, columns 1 and 2
     A(1, 1:2)     # row 1, columns in range 1-2
     A(1, :)       # row 1, all columns

   When a colon is used in the special case of 1-D indexing the result
is always a column vector.  Creating column vectors with a colon index
is a very frequently encountered code idiom and is faster and generally
clearer than calling ‘reshape’ for this case.

     A(:)    # result is column vector: ans = [1; 2; 3; 4]
     A(:)'   # result is row vector: ans = [1, 2, 3, 4]

   In index expressions the keyword ‘end’ automatically refers to the
last entry for a particular dimension.  This magic index can also be
used in ranges and typically eliminates the needs to call ‘size’ or
‘length’ to gather array bounds before indexing.  For example:

     A(1:end/2)        # first half of A => [1, 2]
     A(end + 1) = 5;   # append element
     A(end) = [];      # delete element
     A(1:2:end)        # odd elements of A => [1, 3]
     A(2:2:end)        # even elements of A => [2, 4]
     A(end:-1:1)       # reversal of A => [4, 3, 2, 1]

* Menu:

* Advanced Indexing::


File: octave.info,  Node: Advanced Indexing,  Up: Index Expressions

8.1.1 Advanced Indexing
-----------------------

When it is necessary to extract subsets of entries out of an array whose
indices cannot be written as a Cartesian product of components, linear
indexing together with the function ‘sub2ind’ can be used.  For example:

     A = reshape (1:8, 2, 2, 2)  # Create 3-D array
     A =

     ans(:,:,1) =

        1   3
        2   4

     ans(:,:,2) =

        5   7
        6   8

     A(sub2ind (size (A), [1, 2, 1], [1, 1, 2], [1, 2, 1]))
        ⇒ ans = [A(1, 1, 1), A(2, 1, 2), A(1, 2, 1)]

   An array with ‘nd’ dimensions can be indexed by an index expression
which has from 1 to ‘nd’ components.  For the ordinary and most common
case, the number of components ‘M’ matches the number of dimensions
‘nd’.  In this case the ordinary indexing rules apply and each component
corresponds to the respective dimension of the array.

   However, if the number of indexing components exceeds the number of
dimensions (‘M > nd’) then the excess components must all be singletons
(‘1’).  Moreover, if ‘M < nd’, the behavior is equivalent to reshaping
the input object so as to merge the trailing ‘nd - M’ dimensions into
the last index dimension ‘M’.  Thus, the result will have the
dimensionality of the index expression, and not the original object.
This is the case whenever dimensionality of the index is greater than
one (‘M > 1’), so that the special rules for linear indexing are not
applied.  This is easiest to understand with an example:

     A = reshape (1:8, 2, 2, 2)  # Create 3-D array
     A =

     ans(:,:,1) =

        1   3
        2   4

     ans(:,:,2) =

        5   7
        6   8

     ## 2-D indexing causes third dimension to be merged into second dimension.
     ## Equivalent array for indexing, Atmp, is now 2x4.
     Atmp = reshape (A, 2, 4)
     Atmp =

        1   3   5   7
        2   4   6   8


     A(2,1)   # Reshape to 2x4 matrix, second entry of first column: ans = 2
     A(2,4)   # Reshape to 2x4 matrix, second entry of fourth column: ans = 8
     A(:,:)   # Reshape to 2x4 matrix, select all rows & columns, ans = Atmp

Note here the elegant use of the double colon to replace the call to the
‘reshape’ function.

   Another advanced use of linear indexing is to create arrays filled
with a single value.  This can be done by using an index of ones on a
scalar value.  The result is an object with the dimensions of the index
expression and every element equal to the original scalar.  For example,
the following statements

     a = 13;
     a(ones (1, 4))

produce a row vector whose four elements are all equal to 13.

   Similarly, by indexing a scalar with two vectors of ones it is
possible to create a matrix.  The following statements

     a = 13;
     a(ones (1, 2), ones (1, 3))

create a 2x3 matrix with all elements equal to 13.  This could also have
been written as

     13(ones (2, 3))

   It is more efficient to use indexing rather than the code
construction ‘scalar * ones (M, N, ...)’ because it avoids the
unnecessary multiplication operation.  Moreover, multiplication may not
be defined for the object to be replicated whereas indexing an array is
always defined.  The following code shows how to create a 2x3 cell array
from a base unit which is not itself a scalar.

     {"Hello"}(ones (2, 3))

   It should be noted that ‘ones (1, n)’ (a row vector of ones) results
in a range object (with zero increment).  A range is stored internally
as a starting value, increment, end value, and total number of values;
hence, it is more efficient for storage than a vector or matrix of ones
whenever the number of elements is greater than 4.  In particular, when
‘r’ is a row vector, the expressions

       r(ones (1, n), :)

       r(ones (n, 1), :)

will produce identical results, but the first one will be significantly
faster, at least for ‘r’ and ‘n’ large enough.  In the first case the
index is held in compressed form as a range which allows Octave to
choose a more efficient algorithm to handle the expression.

   A general recommendation for users unfamiliar with these techniques
is to use the function ‘repmat’ for replicating smaller arrays into
bigger ones, which uses such tricks.

   A second use of indexing is to speed up code.  Indexing is a fast
operation and judicious use of it can reduce the requirement for looping
over individual array elements, which is a slow operation.

   Consider the following example which creates a 10-element row vector
a containing the values a(i) = sqrt (i).

     for i = 1:10
       a(i) = sqrt (i);
     endfor

It is quite inefficient to create a vector using a loop like this.  In
this case, it would have been much more efficient to use the expression

     a = sqrt (1:10);

which avoids the loop entirely.

   In cases where a loop cannot be avoided, or a number of values must
be combined to form a larger matrix, it is generally faster to set the
size of the matrix first (pre-allocate storage), and then insert
elements using indexing commands.  For example, given a matrix ‘a’,

     [nr, nc] = size (a);
     x = zeros (nr, n * nc);
     for i = 1:n
       x(:,(i-1)*nc+1:i*nc) = a;
     endfor

is considerably faster than

     x = a;
     for i = 1:n-1
       x = [x, a];
     endfor

because Octave does not have to repeatedly resize the intermediate
result.

 -- : IND = sub2ind (DIMS, I, J)
 -- : IND = sub2ind (DIMS, S1, S2, ..., SN)
     Convert subscripts to linear indices.

     The input DIMS is a dimension vector where each element is the size
     of the array in the respective dimension (*note size: XREFsize.).
     The remaining inputs are scalars or vectors of subscripts to be
     converted.

     The output vector IND contains the converted linear indices.

     Background: Array elements can be specified either by a linear
     index which starts at 1 and runs through the number of elements in
     the array, or they may be specified with subscripts for the row,
     column, page, etc.  The functions ‘ind2sub’ and ‘sub2ind’
     interconvert between the two forms.

     The linear index traverses dimension 1 (rows), then dimension 2
     (columns), then dimension 3 (pages), etc. until it has numbered all
     of the elements.  Consider the following 3-by-3 matrices:

          [(1,1), (1,2), (1,3)]     [1, 4, 7]
          [(2,1), (2,2), (2,3)] ==> [2, 5, 8]
          [(3,1), (3,2), (3,3)]     [3, 6, 9]

     The left matrix contains the subscript tuples for each matrix
     element.  The right matrix shows the linear indices for the same
     matrix.

     The following example shows how to convert the two-dimensional
     indices ‘(2,1)’ and ‘(2,3)’ of a 3-by-3 matrix to linear indices
     with a single call to ‘sub2ind’.

          s1 = [2, 2];
          s2 = [1, 3];
          ind = sub2ind ([3, 3], s1, s2)
              ⇒ ind =  2   8

     See also: *note ind2sub: XREFind2sub, *note size: XREFsize.

 -- : [S1, S2, ..., SN] = ind2sub (DIMS, IND)
     Convert linear indices to subscripts.

     The input DIMS is a dimension vector where each element is the size
     of the array in the respective dimension (*note size: XREFsize.).
     The second input IND contains linear indies to be converted.

     The outputs S1, ..., SN contain the converted subscripts.

     Background: Array elements can be specified either by a linear
     index which starts at 1 and runs through the number of elements in
     the array, or they may be specified with subscripts for the row,
     column, page, etc.  The functions ‘ind2sub’ and ‘sub2ind’
     interconvert between the two forms.

     The linear index traverses dimension 1 (rows), then dimension 2
     (columns), then dimension 3 (pages), etc. until it has numbered all
     of the elements.  Consider the following 3-by-3 matrices:

          [1, 4, 7]     [(1,1), (1,2), (1,3)]
          [2, 5, 8] ==> [(2,1), (2,2), (2,3)]
          [3, 6, 9]     [(3,1), (3,2), (3,3)]

     The left matrix contains the linear indices for each matrix
     element.  The right matrix shows the subscript tuples for the same
     matrix.

     The following example shows how to convert the two-dimensional
     indices ‘(2,1)’ and ‘(2,3)’ of a 3-by-3 matrix to linear indices
     with a single call to ‘sub2ind’.

     The following example shows how to convert the linear indices ‘2’
     and ‘8’ in a 3-by-3 matrix into subscripts.

          ind = [2, 8];
          [r, c] = ind2sub ([3, 3], ind)
              ⇒ r =  2   2
              ⇒ c =  1   3

     If the number of output subscripts exceeds the number of
     dimensions, the exceeded dimensions are set to ‘1’.  On the other
     hand, if fewer subscripts than dimensions are provided, the
     exceeding dimensions are merged into the final requested dimension.
     For clarity, consider the following examples:

          ind  = [2, 8];
          dims = [3, 3];
          ## same as dims = [3, 3, 1]
          [r, c, s] = ind2sub (dims, ind)
              ⇒ r =  2   2
              ⇒ c =  1   3
              ⇒ s =  1   1
          ## same as dims = [9]
          r = ind2sub (dims, ind)
              ⇒ r =  2   8

     See also: *note ind2sub: XREFind2sub, *note size: XREFsize.

 -- : isindex (IND)
 -- : isindex (IND, N)
     Return true if IND is a valid index.

     Valid indices are either positive integers (although possibly of
     real data type), or logical arrays.

     If present, N specifies the maximum extent of the dimension to be
     indexed.  When possible the internal result is cached so that
     subsequent indexing using IND will not perform the check again.

     Implementation Note: Strings are first converted to double values
     before the checks for valid indices are made.  Unless a string
     contains the NULL character "\0", it will always be a valid index.


File: octave.info,  Node: Calling Functions,  Next: Arithmetic Ops,  Prev: Index Expressions,  Up: Expressions

8.2 Calling Functions
=====================

A “function” is a name for a particular calculation.  Because it has a
name, you can ask for it by name at any point in the program.  For
example, the function ‘sqrt’ computes the square root of a number.

   A fixed set of functions are “built-in”, which means they are
available in every Octave program.  The ‘sqrt’ function is one of these.
In addition, you can define your own functions.  *Note Functions and
Scripts::, for information about how to do this.

   The way to use a function is with a “function call” expression, which
consists of the function name followed by a list of “arguments” in
parentheses.  The arguments are expressions which give the raw materials
for the calculation that the function will do.  When there is more than
one argument, they are separated by commas.  If there are no arguments,
you can omit the parentheses, but it is a good idea to include them
anyway, to clearly indicate that a function call was intended.  Here are
some examples:

     sqrt (x^2 + y^2)      # One argument
     ones (n, m)           # Two arguments
     rand ()               # No arguments

   Each function expects a particular number of arguments.  For example,
the ‘sqrt’ function must be called with a single argument, the number to
take the square root of:

     sqrt (ARGUMENT)

   Some of the built-in functions take a variable number of arguments,
depending on the particular usage, and their behavior is different
depending on the number of arguments supplied.

   Like every other expression, the function call has a value, which is
computed by the function based on the arguments you give it.  In this
example, the value of ‘sqrt (ARGUMENT)’ is the square root of the
argument.  A function can also have side effects, such as assigning the
values of certain variables or doing input or output operations.

   Unlike most languages, functions in Octave may return multiple
values.  For example, the following statement

     [u, s, v] = svd (a)

computes the singular value decomposition of the matrix ‘a’ and assigns
the three result matrices to ‘u’, ‘s’, and ‘v’.

   The left side of a multiple assignment expression is itself a list of
expressions, that is, a list of variable names potentially qualified by
index expressions.  See also *note Index Expressions::, and *note
Assignment Ops::.

* Menu:

* Call by Value::
* Recursion::
* Access via Handle::


File: octave.info,  Node: Call by Value,  Next: Recursion,  Up: Calling Functions

8.2.1 Call by Value
-------------------

In Octave, unlike Fortran, function arguments are passed by value, which
means that each argument in a function call is evaluated and assigned to
a temporary location in memory before being passed to the function.
There is currently no way to specify that a function parameter should be
passed by reference instead of by value.  This means that it is
impossible to directly alter the value of a function parameter in the
calling function.  It can only change the local copy within the function
body.  For example, the function

     function f (x, n)
       while (n-- > 0)
         disp (x);
       endwhile
     endfunction

displays the value of the first argument N times.  In this function, the
variable N is used as a temporary variable without having to worry that
its value might also change in the calling function.  Call by value is
also useful because it is always possible to pass constants for any
function parameter without first having to determine that the function
will not attempt to modify the parameter.

   The caller may use a variable as the expression for the argument, but
the called function does not know this: it only knows what value the
argument had.  For example, given a function called as

     foo = "bar";
     fcn (foo)

you should not think of the argument as being “the variable ‘foo’.”
Instead, think of the argument as the string value, "bar".

   Even though Octave uses pass-by-value semantics for function
arguments, values are not copied unnecessarily.  For example,

     x = rand (1000);
     f (x);

does not actually force two 1000 by 1000 element matrices to exist
_unless_ the function ‘f’ modifies the value of its argument.  Then
Octave must create a copy to avoid changing the value outside the scope
of the function ‘f’, or attempting (and probably failing!)  to modify
the value of a constant or the value of a temporary result.


File: octave.info,  Node: Recursion,  Next: Access via Handle,  Prev: Call by Value,  Up: Calling Functions

8.2.2 Recursion
---------------

With some restrictions(1), recursive function calls are allowed.  A
“recursive function” is one which calls itself, either directly or
indirectly.  For example, here is an inefficient(2) way to compute the
factorial of a given integer:

     function retval = fact (n)
       if (n > 0)
         retval = n * fact (n-1);
       else
         retval = 1;
       endif
     endfunction

This function is recursive because it calls itself directly.  It
eventually terminates because each time it calls itself, it uses an
argument that is one less than was used for the previous call.  Once the
argument is no longer greater than zero, it does not call itself, and
the recursion ends.

   The built-in variable ‘max_recursion_depth’ specifies a limit to the
recursion depth and prevents Octave from recursing infinitely.
Similarly, the variable ‘max_stack_depth’ specifies a limit to the depth
of function calls, whether recursive or not.  These limits help prevent
stack overflow on the computer Octave is running on, so that instead of
exiting with a signal, the interpreter will throw an error and return to
the command prompt.

 -- : VAL = max_recursion_depth ()
 -- : OLD_VAL = max_recursion_depth (NEW_VAL)
 -- : max_recursion_depth (NEW_VAL, "local")
     Query or set the internal limit on the number of times a function
     may be called recursively.

     If the limit is exceeded, an error message is printed and control
     returns to the top level.

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

 -- : VAL = max_stack_depth ()
 -- : OLD_VAL = max_stack_depth (NEW_VAL)
 -- : max_stack_depth (NEW_VAL, "local")
     Query or set the internal limit on the number of times a function
     may be called recursively.

     If the limit is exceeded, an error message is printed and control
     returns to the top level.

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

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

   (1) Some of Octave’s functions are implemented in terms of functions
that cannot be called recursively.  For example, the ODE solver ‘lsode’
is ultimately implemented in a Fortran subroutine that cannot be called
recursively, so ‘lsode’ should not be called either directly or
indirectly from within the user-supplied function that ‘lsode’ requires.
Doing so will result in an error.

   (2) It would be much better to use ‘prod (1:n)’, or ‘gamma (n+1)’
instead, after first checking to ensure that the value ‘n’ is actually a
positive integer.


File: octave.info,  Node: Access via Handle,  Prev: Recursion,  Up: Calling Functions

8.2.3 Access via Handle
-----------------------

A function may be abstracted and referenced via a function handle
acquired using the special operator ‘@’.  For example,

     f = @plus;
     f (2, 2)
     ⇒  4

is equivalent to calling ‘plus (2, 2)’ directly.  Beyond abstraction for
general programming, function handles find use in callback methods for
figures and graphics by adding listeners to properties or assigning
pre-existing actions, such as in the following example:

     function mydeletefcn (h, ~, msg)
       printf (msg);
     endfunction
     sombrero;
     set (gcf, "deletefcn", {@mydeletefcn, "Bye!\n"});
     close;

The above will print "Bye!"  to the terminal upon the closing (deleting)
of the figure.  There are many graphics property actions for which a
callback function may be assigned, including, ‘buttondownfcn’,
‘windowscrollwheelfcn’, ‘createfcn’, ‘deletefcn’, ‘keypressfcn’, etc.

   Note that the ‘@’ character also plays a role in defining class
functions, i.e., methods, but not as a syntactical element.  Rather it
begins a directory name containing methods for a class that shares the
directory name sans the ‘@’ character.  See *note Object Oriented
Programming::.


File: octave.info,  Node: Arithmetic Ops,  Next: Comparison Ops,  Prev: Calling Functions,  Up: Expressions

8.3 Arithmetic Operators
========================

The following arithmetic operators are available, and work on scalars
and matrices.  The element-by-element operators and functions broadcast
(*note Broadcasting::).

X + Y
     Addition.  If both operands are matrices, the number of rows and
     columns must both agree, or they must be broadcastable to the same
     shape.

X .+ Y
     Element-by-element addition.  This operator is equivalent to ‘+’.

X - Y
     Subtraction.  If both operands are matrices, the number of rows and
     columns of both must agree, or they must be broadcastable to the
     same shape.

X .- Y
     Element-by-element subtraction.  This operator is equivalent to
     ‘-’.

X * Y
     Matrix multiplication.  The number of columns of X must agree with
     the number of rows of Y.

X .* Y
     Element-by-element multiplication.  If both operands are matrices,
     the number of rows and columns must both agree, or they must be
     broadcastable to the same shape.

X / Y
     Right division.  This is conceptually equivalent to the expression

          (inverse (y') * x')'

     but it is computed without forming the inverse of Y’.

     If the system is not square, or if the coefficient matrix is
     singular, a minimum norm solution is computed.

X ./ Y
     Element-by-element right division.

X \ Y
     Left division.  This is conceptually equivalent to the expression

          inverse (x) * y

     but it is computed without forming the inverse of X.

     If the system is not square, or if the coefficient matrix is
     singular, a minimum norm solution is computed.

X .\ Y
     Element-by-element left division.  Each element of Y is divided by
     each corresponding element of X.

X ^ Y
X ** Y
     Power operator.  If X and Y are both scalars, this operator returns
     X raised to the power Y.  If X is a scalar and Y is a square
     matrix, the result is computed using an eigenvalue expansion.  If X
     is a square matrix, the result is computed by repeated
     multiplication if Y is an integer, and by an eigenvalue expansion
     if Y is not an integer.  An error results if both X and Y are
     matrices.

     The implementation of this operator needs to be improved.

X .^ Y
X .** Y
     Element-by-element power operator.  If both operands are matrices,
     the number of rows and columns must both agree, or they must be
     broadcastable to the same shape.  If several complex results are
     possible, the one with smallest non-negative argument (angle) is
     taken.  This rule may return a complex root even when a real root
     is also possible.  Use ‘realpow’, ‘realsqrt’, ‘cbrt’, or ‘nthroot’
     if a real result is preferred.

-X
     Negation.

+X
     Unary plus.  This operator has no effect on the operand.

X’
     Complex conjugate transpose.  For real arguments, this operator is
     the same as the transpose operator.  For complex arguments, this
     operator is equivalent to the expression

          conj (x.')

X.’
     Transpose.

   Note that because Octave’s element-by-element operators begin with a
‘.’, there is a possible ambiguity for statements like

     1./m

because the period could be interpreted either as part of the constant
or as part of the operator.  To resolve this conflict, Octave treats the
expression as if you had typed

     (1) ./ m

and not

     (1.) / m

Although this is inconsistent with the normal behavior of Octave’s
lexer, which usually prefers to break the input into tokens by
preferring the longest possible match at any given point, it is more
useful in this case.

 -- : ctranspose (X)
     Return the complex conjugate transpose of X.

     This function and X’ are equivalent.

     See also: *note transpose: XREFtranspose.

 -- : ldivide (X, Y)
     Return the element-by-element left division of X and Y.

     This function and X .\ Y are equivalent.

     See also: *note rdivide: XREFrdivide, *note mldivide: XREFmldivide,
     *note times: XREFtimes, *note plus: XREFplus.

 -- : minus (X, Y)
     This function and X - Y are equivalent.

     See also: *note plus: XREFplus, *note uminus: XREFuminus.

 -- : mldivide (X, Y)
     Return the matrix left division of X and Y.

     This function and X \ Y are equivalent.

     See also: *note mrdivide: XREFmrdivide, *note ldivide: XREFldivide,
     *note rdivide: XREFrdivide.

 -- : mpower (X, Y)
     Return the matrix power operation of X raised to the Y power.

     This function and X ^ Y are equivalent.

     See also: *note power: XREFpower, *note mtimes: XREFmtimes, *note
     plus: XREFplus, *note minus: XREFminus.

 -- : mrdivide (X, Y)
     Return the matrix right division of X and Y.

     This function and X / Y are equivalent.

     See also: *note mldivide: XREFmldivide, *note rdivide: XREFrdivide,
     *note plus: XREFplus, *note minus: XREFminus.

 -- : mtimes (X, Y)
 -- : mtimes (X1, X2, ...)
     Return the matrix multiplication product of inputs.

     This function and X * Y are equivalent.  If more arguments are
     given, the multiplication is applied cumulatively from left to
     right:

          (...((X1 * X2) * X3) * ...)

     At least one argument is required.

     See also: *note times: XREFtimes, *note plus: XREFplus, *note
     minus: XREFminus, *note rdivide: XREFrdivide, *note mrdivide:
     XREFmrdivide, *note mldivide: XREFmldivide, *note mpower:
     XREFmpower.

 -- : plus (X, Y)
 -- : plus (X1, X2, ...)
     This function and X + Y are equivalent.

     If more arguments are given, the summation is applied cumulatively
     from left to right:

          (...((X1 + X2) + X3) + ...)

     At least one argument is required.

     See also: *note minus: XREFminus, *note uplus: XREFuplus.

 -- : power (X, Y)
     Return the element-by-element operation of X raised to the Y power.

     This function and X .^ Y are equivalent.

     If several complex results are possible, returns the one with
     smallest non-negative argument (angle).  Use ‘realpow’, ‘realsqrt’,
     ‘cbrt’, or ‘nthroot’ if a real result is preferred.

     See also: *note mpower: XREFmpower, *note realpow: XREFrealpow,
     *note realsqrt: XREFrealsqrt, *note cbrt: XREFcbrt, *note nthroot:
     XREFnthroot.

 -- : rdivide (X, Y)
     Return the element-by-element right division of X and Y.

     This function and X ./ Y are equivalent.

     See also: *note ldivide: XREFldivide, *note mrdivide: XREFmrdivide,
     *note times: XREFtimes, *note plus: XREFplus.

 -- : times (X, Y)
 -- : times (X1, X2, ...)
     Return the element-by-element multiplication product of inputs.

     This function and X .* Y are equivalent.  If more arguments are
     given, the multiplication is applied cumulatively from left to
     right:

          (...((X1 .* X2) .* X3) .* ...)

     At least one argument is required.

     See also: *note mtimes: XREFmtimes, *note rdivide: XREFrdivide.

 -- : transpose (X)
     Return the transpose of X.

     This function and X.’ are equivalent.

     See also: *note ctranspose: XREFctranspose.

 -- : uminus (X)
     This function and - X are equivalent.

     See also: *note uplus: XREFuplus, *note minus: XREFminus.

 -- : uplus (X)
     This function and + X are equivalent.

     See also: *note uminus: XREFuminus, *note plus: XREFplus, *note
     minus: XREFminus.


File: octave.info,  Node: Comparison Ops,  Next: Boolean Expressions,  Prev: Arithmetic Ops,  Up: Expressions

8.4 Comparison Operators
========================

“Comparison operators” compare numeric values for relationships such as
equality.  They are written using _relational operators_.

   All of Octave’s comparison operators return a value of 1 if the
comparison is true, or 0 if it is false.  For matrix values, they all
work on an element-by-element basis.  Broadcasting rules apply.  *Note
Broadcasting::.  For example:

     [1, 2; 3, 4] == [1, 3; 2, 4]
          ⇒  1  0
              0  1

   According to broadcasting rules, if one operand is a scalar and the
other is a matrix, the scalar is compared to each element of the matrix
in turn, and the result is the same size as the matrix.

‘X < Y’
     True if X is less than Y.

‘X <= Y’
     True if X is less than or equal to Y.

‘X == Y’
     True if X is equal to Y.

‘X >= Y’
     True if X is greater than or equal to Y.

‘X > Y’
     True if X is greater than Y.

‘X != Y’
‘X ~= Y’
     True if X is not equal to Y.

   For complex numbers, the following ordering is defined: Z1 < Z2 if
and only if

       abs (Z1) < abs (Z2)
       || (abs (Z1) == abs (Z2) && arg (Z1) < arg (Z2))

   This is consistent with the ordering used by “max”, “min” and “sort”,
but is not consistent with MATLAB, which only compares the real parts.

   String comparisons may also be performed with the ‘strcmp’ function,
not with the comparison operators listed above.  *Note Strings::.

 -- : eq (X, Y)
     Return true if the two inputs are equal.

     This function is equivalent to ‘X == Y’.

     See also: *note ne: XREFne, *note isequal: XREFisequal, *note le:
     XREFle, *note ge: XREFge, *note gt: XREFgt, *note ne: XREFne, *note
     lt: XREFlt.

 -- : ge (X, Y)
     This function is equivalent to ‘X >= Y’.

     See also: *note le: XREFle, *note eq: XREFeq, *note gt: XREFgt,
     *note ne: XREFne, *note lt: XREFlt.

 -- : gt (X, Y)
     This function is equivalent to ‘X > Y’.

     See also: *note le: XREFle, *note eq: XREFeq, *note ge: XREFge,
     *note ne: XREFne, *note lt: XREFlt.

 -- : isequal (X1, X2, ...)
     Return true if all of X1, X2, ... are equal.

     See also: *note isequaln: XREFisequaln.

 -- : isequaln (X1, X2, ...)
     Return true if all of X1, X2, ... are equal under the additional
     assumption that NaN == NaN (no comparison of NaN placeholders in
     dataset).

     See also: *note isequal: XREFisequal.

 -- : le (X, Y)
     This function is equivalent to ‘X <= Y’.

     See also: *note eq: XREFeq, *note ge: XREFge, *note gt: XREFgt,
     *note ne: XREFne, *note lt: XREFlt.

 -- : lt (X, Y)
     This function is equivalent to ‘X < Y’.

     See also: *note le: XREFle, *note eq: XREFeq, *note ge: XREFge,
     *note gt: XREFgt, *note ne: XREFne.

 -- : ne (X, Y)
     Return true if the two inputs are not equal.

     This function is equivalent to ‘X != Y’.

     See also: *note eq: XREFeq, *note isequal: XREFisequal, *note le:
     XREFle, *note ge: XREFge, *note lt: XREFlt.


File: octave.info,  Node: Boolean Expressions,  Next: Assignment Ops,  Prev: Comparison Ops,  Up: Expressions

8.5 Boolean Expressions
=======================

* Menu:

* Element-by-element Boolean Operators::
* Short-circuit Boolean Operators::


File: octave.info,  Node: Element-by-element Boolean Operators,  Next: Short-circuit Boolean Operators,  Up: Boolean Expressions

8.5.1 Element-by-element Boolean Operators
------------------------------------------

An “element-by-element boolean expression” is a combination of
comparison expressions using the boolean operators “or” (‘|’), “and”
(‘&’), and “not” (‘!’), along with parentheses to control nesting.  The
truth of the boolean expression is computed by combining the truth
values of the corresponding elements of the component expressions.  A
value is considered to be false if it is zero, and true otherwise.

   Element-by-element boolean expressions can be used wherever
comparison expressions can be used.  They can be used in ‘if’ and
‘while’ statements.  However, a matrix value used as the condition in an
‘if’ or ‘while’ statement is only true if _all_ of its elements are
nonzero.

   Like comparison operations, each element of an element-by-element
boolean expression also has a numeric value (1 if true, 0 if false) that
comes into play if the result of the boolean expression is stored in a
variable, or used in arithmetic.

   Here are descriptions of the three element-by-element boolean
operators.

‘BOOLEAN1 & BOOLEAN2’
     Elements of the result are true if both corresponding elements of
     BOOLEAN1 and BOOLEAN2 are true.

‘BOOLEAN1 | BOOLEAN2’
     Elements of the result are true if either of the corresponding
     elements of BOOLEAN1 or BOOLEAN2 is true.

‘! BOOLEAN’
‘~ BOOLEAN’
     Each element of the result is true if the corresponding element of
     BOOLEAN is false.

   These operators work on an element-by-element basis.  For example,
the expression

     [1, 0; 0, 1] & [1, 0; 2, 3]

returns a two by two identity matrix.

   For the binary operators, broadcasting rules apply.  *Note
Broadcasting::.  In particular, if one of the operands is a scalar and
the other a matrix, the operator is applied to the scalar and each
element of the matrix.

   For the binary element-by-element boolean operators, both
subexpressions BOOLEAN1 and BOOLEAN2 are evaluated before computing the
result.  This can make a difference when the expressions have side
effects.  For example, in the expression

     a & b++

the value of the variable B is incremented even if the variable A is
zero.

   This behavior is necessary for the boolean operators to work as
described for matrix-valued operands.

 -- : Z = and (X, Y)
 -- : Z = and (X1, X2, ...)
     Return the logical AND of X and Y.

     This function is equivalent to the operator syntax ‘X & Y’.  If
     more than two arguments are given, the logical AND is applied
     cumulatively from left to right:

          (...((X1 & X2) & X3) & ...)

     At least one argument is required.

     See also: *note or: XREFor, *note not: XREFnot, *note xor: XREFxor.

 -- : Z = not (X)
     Return the logical NOT of X.

     This function is equivalent to the operator syntax ‘! X’.

     See also: *note and: XREFand, *note or: XREFor, *note xor: XREFxor.

 -- : Z = or (X, Y)
 -- : Z = or (X1, X2, ...)
     Return the logical OR of X and Y.

     This function is equivalent to the operator syntax ‘X | Y’.  If
     more than two arguments are given, the logical OR is applied
     cumulatively from left to right:

          (...((X1 | X2) | X3) | ...)

     At least one argument is required.

     See also: *note and: XREFand, *note not: XREFnot, *note xor:
     XREFxor.


File: octave.info,  Node: Short-circuit Boolean Operators,  Prev: Element-by-element Boolean Operators,  Up: Boolean Expressions

8.5.2 Short-circuit Boolean Operators
-------------------------------------

Combined with the implicit conversion to scalar values in ‘if’ and
‘while’ conditions, Octave’s element-by-element boolean operators are
often sufficient for performing most logical operations.  However, it is
sometimes desirable to stop evaluating a boolean expression as soon as
the overall truth value can be determined.  Octave’s “short-circuit”
boolean operators work this way.

‘BOOLEAN1 && BOOLEAN2’
     The expression BOOLEAN1 is evaluated and converted to a scalar
     using the equivalent of the operation ‘all (BOOLEAN1(:))’.  If it
     is false, the result of the overall expression is 0.  If it is
     true, the expression BOOLEAN2 is evaluated and converted to a
     scalar using the equivalent of the operation ‘all (BOOLEAN2(:))’.
     If it is true, the result of the overall expression is 1.
     Otherwise, the result of the overall expression is 0.

     *Warning:* there is one exception to the rule of evaluating ‘all
     (BOOLEAN1(:))’, which is when ‘boolean1’ is the empty matrix.  The
     truth value of an empty matrix is always ‘false’ so ‘[] && true’
     evaluates to ‘false’ even though ‘all ([])’ is ‘true’.

‘BOOLEAN1 || BOOLEAN2’
     The expression BOOLEAN1 is evaluated and converted to a scalar
     using the equivalent of the operation ‘all (BOOLEAN1(:))’.  If it
     is true, the result of the overall expression is 1.  If it is
     false, the expression BOOLEAN2 is evaluated and converted to a
     scalar using the equivalent of the operation ‘all (BOOLEAN2(:))’.
     If it is true, the result of the overall expression is 1.
     Otherwise, the result of the overall expression is 0.

     *Warning:* the truth value of an empty matrix is always ‘false’,
     see the previous list item for details.

   The fact that both operands may not be evaluated before determining
the overall truth value of the expression can be important.  For
example, in the expression

     a && b++

the value of the variable B is only incremented if the variable A is
nonzero.

   This can be used to write somewhat more concise code.  For example,
it is possible write

     function f (a, b, c)
       if (nargin > 2 && ischar (c))
         ...

instead of having to use two ‘if’ statements to avoid attempting to
evaluate an argument that doesn’t exist.  For example, without the
short-circuit feature, it would be necessary to write

     function f (a, b, c)
       if (nargin > 2)
         if (ischar (c))
           ...

Writing

     function f (a, b, c)
       if (nargin > 2 & ischar (c))
         ...

would result in an error if ‘f’ were called with one or two arguments
because Octave would be forced to try to evaluate both of the operands
for the operator ‘&’.

   MATLAB has special behavior that allows the operators ‘&’ and ‘|’ to
short-circuit when used in the truth expression for ‘if’ and ‘while’
statements.  Octave behaves the same way for compatibility, however, the
use of the ‘&’ and ‘|’ operators in this way is strongly discouraged and
a warning will be issued.  Instead, you should use the ‘&&’ and ‘||’
operators that always have short-circuit behavior.

   Finally, the ternary operator (?:) is not supported in Octave.  If
short-circuiting is not important, it can be replaced by the ‘ifelse’
function.

 -- : merge (MASK, TVAL, FVAL)
 -- : ifelse (MASK, TVAL, FVAL)
     Merge elements of TRUE_VAL and FALSE_VAL, depending on the value of
     MASK.

     If MASK is a logical scalar, the other two arguments can be
     arbitrary values.  Otherwise, MASK must be a logical array, and
     TVAL, FVAL should be arrays of matching class, or cell arrays.  In
     the scalar mask case, TVAL is returned if MASK is true, otherwise
     FVAL is returned.

     In the array mask case, both TVAL and FVAL must be either scalars
     or arrays with dimensions equal to MASK.  The result is constructed
     as follows:

          result(mask) = tval(mask);
          result(! mask) = fval(! mask);

     MASK can also be arbitrary numeric type, in which case it is first
     converted to logical.

     See also: *note logical: XREFlogical, *note diff: XREFdiff.


File: octave.info,  Node: Assignment Ops,  Next: Increment Ops,  Prev: Boolean Expressions,  Up: Expressions

8.6 Assignment Expressions
==========================

An “assignment” is an expression that stores a new value into a
variable.  For example, the following expression assigns the value 1 to
the variable ‘z’:

     z = 1

After this expression is executed, the variable ‘z’ has the value 1.
Whatever old value ‘z’ had before the assignment is forgotten.  The ‘=’
sign is called an “assignment operator”.

   Assignments can store string values also.  For example, the following
expression would store the value "this food is good" in the variable
‘message’:

     thing = "food"
     predicate = "good"
     message = [ "this " , thing , " is " , predicate ]

(This also illustrates concatenation of strings.)

   Most operators (addition, concatenation, and so on) have no effect
except to compute a value.  If you ignore the value, you might as well
not use the operator.  An assignment operator is different.  It does
produce a value, but even if you ignore the value, the assignment still
makes itself felt through the alteration of the variable.  We call this
a “side effect”.

   The left-hand operand of an assignment need not be a variable (*note
Variables::).  It can also be an element of a matrix (*note Index
Expressions::) or a list of return values (*note Calling Functions::).
These are all called “lvalues”, which means they can appear on the
left-hand side of an assignment operator.  The right-hand operand may be
any expression.  It produces the new value which the assignment stores
in the specified variable, matrix element, or list of return values.

   It is important to note that variables do _not_ have permanent types.
The type of a variable is simply the type of whatever value it happens
to hold at the moment.  In the following program fragment, the variable
‘foo’ has a numeric value at first, and a string value later on:

     octave:13> foo = 1
     foo = 1
     octave:13> foo = "bar"
     foo = bar

When the second assignment gives ‘foo’ a string value, the fact that it
previously had a numeric value is forgotten.

   Assignment of a scalar to an indexed matrix sets all of the elements
that are referenced by the indices to the scalar value.  For example, if
‘a’ is a matrix with at least two columns,

     a(:, 2) = 5

sets all the elements in the second column of ‘a’ to 5.

   Assigning an empty matrix ‘[]’ works in most cases to allow you to
delete rows or columns of matrices and vectors.  *Note Empty Matrices::.
For example, given a 4 by 5 matrix A, the assignment

     A (3, :) = []

deletes the third row of A, and the assignment

     A (:, 1:2:5) = []

deletes the first, third, and fifth columns.

   An assignment is an expression, so it has a value.  Thus, ‘z = 1’ as
an expression has the value 1.  One consequence of this is that you can
write multiple assignments together:

     x = y = z = 0

stores the value 0 in all three variables.  It does this because the
value of ‘z = 0’, which is 0, is stored into ‘y’, and then the value of
‘y = z = 0’, which is 0, is stored into ‘x’.

   This is also true of assignments to lists of values, so the following
is a valid expression

     [a, b, c] = [u, s, v] = svd (a)

that is exactly equivalent to

     [u, s, v] = svd (a)
     a = u
     b = s
     c = v

   In expressions like this, the number of values in each part of the
expression need not match.  For example, the expression

     [a, b] = [u, s, v] = svd (a)

is equivalent to

     [u, s, v] = svd (a)
     a = u
     b = s

The number of values on the left side of the expression can, however,
not exceed the number of values on the right side.  For example, the
following will produce an error.

     [a, b, c, d] = [u, s, v] = svd (a);
     ⊣ error: element number 4 undefined in return list

   The symbol ‘~’ may be used as a placeholder in the list of lvalues,
indicating that the corresponding return value should be ignored and not
stored anywhere:

     [~, s, v] = svd (a);

   This is cleaner and more memory efficient than using a dummy
variable.  The ‘nargout’ value for the right-hand side expression is not
affected.  If the assignment is used as an expression, the return value
is a comma-separated list with the ignored values dropped.

   A very common programming pattern is to increment an existing
variable with a given value, like this

     a = a + 2;

This can be written in a clearer and more condensed form using the ‘+=’
operator

     a += 2;

Similar operators also exist for subtraction (‘-=’), multiplication
(‘*=’), and division (‘/=’).  An expression of the form

     EXPR1 OP= EXPR2

is evaluated as

     EXPR1 = (EXPR1) OP (EXPR2)

where OP can be either ‘+’, ‘-’, ‘*’, or ‘/’, as long as EXPR2 is a
simple expression with no side effects.  If EXPR2 also contains an
assignment operator, then this expression is evaluated as

     TEMP = EXPR2
     EXPR1 = (EXPR1) OP TEMP

where TEMP is a placeholder temporary value storing the computed result
of evaluating EXPR2.  So, the expression

     a *= b+1

is evaluated as

     a = a * (b+1)

and _not_

     a = a * b + 1

   You can use an assignment anywhere an expression is called for.  For
example, it is valid to write ‘x != (y = 1)’ to set ‘y’ to 1 and then
test whether ‘x’ equals 1.  But this style tends to make programs hard
to read.  Except in a one-shot program, you should rewrite it to get rid
of such nesting of assignments.  This is never very hard.


File: octave.info,  Node: Increment Ops,  Next: Operator Precedence,  Prev: Assignment Ops,  Up: Expressions

8.7 Increment Operators
=======================

_Increment operators_ increase or decrease the value of a variable by 1.
The operator to increment a variable is written as ‘++’.  It may be used
to increment a variable either before or after taking its value.

   For example, to pre-increment the variable X, you would write ‘++X’.
This would add one to X and then return the new value of X as the result
of the expression.  It is exactly the same as the expression ‘X = X +
1’.

   To post-increment a variable X, you would write ‘X++’.  This adds one
to the variable X, but returns the value that X had prior to
incrementing it.  For example, if X is equal to 2, the result of the
expression ‘X++’ is 2, and the new value of X is 3.

   For matrix and vector arguments, the increment and decrement
operators work on each element of the operand.

   Here is a list of all the increment and decrement expressions.

‘++X’
     This expression increments the variable X.  The value of the
     expression is the _new_ value of X.  It is equivalent to the
     expression ‘X = X + 1’.

‘--X’
     This expression decrements the variable X.  The value of the
     expression is the _new_ value of X.  It is equivalent to the
     expression ‘X = X - 1’.

‘X++’
     This expression causes the variable X to be incremented.  The value
     of the expression is the _old_ value of X.

‘X--’
     This expression causes the variable X to be decremented.  The value
     of the expression is the _old_ value of X.


File: octave.info,  Node: Operator Precedence,  Prev: Increment Ops,  Up: Expressions

8.8 Operator Precedence
=======================

“Operator precedence” determines how operators are grouped, when
different operators appear close by in one expression.  For example, ‘*’
has higher precedence than ‘+’.  Thus, the expression ‘a + b * c’ means
to multiply ‘b’ and ‘c’, and then add ‘a’ to the product (i.e., ‘a + (b
* c)’).

   You can overrule the precedence of the operators by using
parentheses.  You can think of the precedence rules as saying where the
parentheses are assumed if you do not write parentheses yourself.  In
fact, it is wise to use parentheses whenever you have an unusual
combination of operators, because other people who read the program may
not remember what the precedence is in this case.  You might forget as
well, and then you too could make a mistake.  Explicit parentheses will
help prevent any such mistake.

   When operators of equal precedence are used together, the leftmost
operator groups first, except for the assignment operators, which group
in the opposite order.  Thus, the expression ‘a - b + c’ groups as ‘(a -
b) + c’, but the expression ‘a = b = c’ groups as ‘a = (b = c)’.

   The precedence of prefix unary operators is important when another
operator follows the operand.  For example, ‘-x^2’ means ‘-(x^2)’,
because ‘-’ has lower precedence than ‘^’.

   Here is a table of the operators in Octave, in order of decreasing
precedence.  Unless noted, all operators group left to right.

‘function call and array indexing, cell array indexing, and structure element indexing’
     ‘()’ ‘{}’ ‘.’

‘postfix increment, and postfix decrement’
     ‘++’ ‘--’

     These operators group right to left.

‘transpose and exponentiation’
     ‘'’ ‘.'’  ‘^’ ‘**’ ‘.^’ ‘.**’

‘unary plus, unary minus, prefix increment, prefix decrement, and logical "not"’
     ‘+’ ‘-’ ‘++’ ‘--’ ‘~’ ‘!’

‘multiply and divide’
     ‘*’ ‘/’ ‘\’ ‘.\’ ‘.*’ ‘./’

‘add, subtract’
     ‘+’ ‘-’

‘colon’
     ‘:’

‘relational’
     ‘<’ ‘<=’ ‘==’ ‘>=’ ‘>’ ‘!=’ ‘~=’

‘element-wise "and"’
     ‘&’

‘element-wise "or"’
     ‘|’

‘logical "and"’
     ‘&&’

‘logical "or"’
     ‘||’

‘assignment’
     ‘=’ ‘+=’ ‘-=’ ‘*=’ ‘/=’ ‘\=’ ‘^=’ ‘.*=’ ‘./=’ ‘.\=’ ‘.^=’ ‘|=’ ‘&=’

     These operators group right to left.


File: octave.info,  Node: Evaluation,  Next: Statements,  Prev: Expressions,  Up: Top

9 Evaluation
************

Normally, you evaluate expressions simply by typing them at the Octave
prompt, or by asking Octave to interpret commands that you have saved in
a file.

   Sometimes, you may find it necessary to evaluate an expression that
has been computed and stored in a string, which is exactly what the
‘eval’ function lets you do.

 -- : eval (TRY)
 -- : eval (TRY, CATCH)
     Parse the string TRY and evaluate it as if it were an Octave
     program.

     If execution fails, evaluate the optional string CATCH.

     The string TRY is evaluated in the current context, so any results
     remain available after ‘eval’ returns.

     The following example creates the variable A with the approximate
     value of 3.1416 in the current workspace.

          eval ("A = acos(-1);");

     If an error occurs during the evaluation of TRY then the CATCH
     string is evaluated, as the following example shows:

          eval ('error ("This is a bad example");',
                'printf ("This error occurred:\n%s\n", lasterr ());');
               ⊣ This error occurred:
                  This is a bad example

     Programming Note: if you are only using ‘eval’ as an
     error-capturing mechanism, rather than for the execution of
     arbitrary code strings, Consider using try/catch blocks or
     unwind_protect/unwind_protect_cleanup blocks instead.  These
     techniques have higher performance and don’t introduce the security
     considerations that the evaluation of arbitrary code does.

     See also: *note evalin: XREFevalin, *note evalc: XREFevalc, *note
     assignin: XREFassignin, *note feval: XREFfeval.

   The ‘evalc’ function additionally captures any console output
produced by the evaluated expression.

 -- : S = evalc (TRY)
 -- : S = evalc (TRY, CATCH)
     Parse and evaluate the string TRY as if it were an Octave program,
     while capturing the output into the return variable S.

     If execution fails, evaluate the optional string CATCH.

     This function behaves like ‘eval’, but any output or warning
     messages which would normally be written to the console are
     captured and returned in the string S.

     The ‘diary’ is disabled during the execution of this function.
     When ‘system’ is used, any output produced by external programs is
     _not_ captured, unless their output is captured by the ‘system’
     function itself.

          s = evalc ("t = 42"), t
            ⇒ s = t =  42

            ⇒ t =  42

     See also: *note eval: XREFeval, *note diary: XREFdiary.

* Menu:

* Calling a Function by its Name::
* Evaluation in a Different Context::


File: octave.info,  Node: Calling a Function by its Name,  Next: Evaluation in a Different Context,  Up: Evaluation

9.1 Calling a Function by its Name
==================================

The ‘feval’ function allows you to call a function from a string
containing its name.  This is useful when writing a function that needs
to call user-supplied functions.  The ‘feval’ function takes the name of
the function to call as its first argument, and the remaining arguments
are given to the function.

   The following example is a simple-minded function using ‘feval’ that
finds the root of a user-supplied function of one variable using
Newton’s method.

     function result = newtroot (fname, x)

     # usage: newtroot (fname, x)
     #
     #   fname : a string naming a function f(x).
     #   x     : initial guess

       delta = tol = sqrt (eps);
       maxit = 200;
       fx = feval (fname, x);
       for i = 1:maxit
         if (abs (fx) < tol)
           result = x;
           return;
         else
           fx_new = feval (fname, x + delta);
           deriv = (fx_new - fx) / delta;
           x = x - fx / deriv;
           fx = fx_new;
         endif
       endfor

       result = x;

     endfunction

   Note that this is only meant to be an example of calling
user-supplied functions and should not be taken too seriously.  In
addition to using a more robust algorithm, any serious code would check
the number and type of all the arguments, ensure that the supplied
function really was a function, etc.  *Note Predicates for Numeric
Objects::, for a list of predicates for numeric objects, and *note
Status of Variables::, for a description of the ‘exist’ function.

 -- : feval (NAME, ...)
     Evaluate the function named NAME.

     Any arguments after the first are passed as inputs to the named
     function.  For example,

          feval ("acos", -1)
               ⇒ 3.1416

     calls the function ‘acos’ with the argument ‘-1’.

     The function ‘feval’ can also be used with function handles of any
     sort (*note Function Handles::).  Historically, ‘feval’ was the
     only way to call user-supplied functions in strings, but function
     handles are now preferred due to the cleaner syntax they offer.
     For example,

          F = @exp;
          feval (F, 1)
              ⇒ 2.7183
          F (1)
              ⇒ 2.7183

     are equivalent ways to call the function referred to by F.  If it
     cannot be predicted beforehand whether F is a function handle,
     function name in a string, or inline function then ‘feval’ can be
     used instead.

   A similar function ‘run’ exists for calling user script files, that
are not necessarily on the user path

 -- : run SCRIPT
 -- : run ("SCRIPT")
     Run SCRIPT in the current workspace.

     Scripts which reside in directories specified in Octave’s load
     path, and which end with the extension ‘".m"’, can be run simply by
     typing their name.  For scripts not located on the load path, use
     ‘run’.

     The filename SCRIPT can be a bare, fully qualified, or relative
     filename and with or without a file extension.  If no extension is
     specified, Octave will first search for a script with the ‘".m"’
     extension before falling back to the script name without an
     extension.

     Implementation Note: If SCRIPT includes a path component, then
     ‘run’ first changes the working directory to the directory where
     SCRIPT is found.  Next, the script is executed.  Finally, ‘run’
     returns to the original working directory unless SCRIPT has
     specifically changed directories.

     See also: *note path: XREFpath, *note addpath: XREFaddpath, *note
     source: XREFsource.


File: octave.info,  Node: Evaluation in a Different Context,  Prev: Calling a Function by its Name,  Up: Evaluation

9.2 Evaluation in a Different Context
=====================================

Before you evaluate an expression you need to substitute the values of
the variables used in the expression.  These are stored in the symbol
table.  Whenever the interpreter starts a new function it saves the
current symbol table and creates a new one, initializing it with the
list of function parameters and a couple of predefined variables such as
‘nargin’.  Expressions inside the function use the new symbol table.

   Sometimes you want to write a function so that when you call it, it
modifies variables in your own context.  This allows you to use a
pass-by-name style of function, which is similar to using a pointer in
programming languages such as C.

   Consider how you might write ‘save’ and ‘load’ as m-files.  For
example:

     function create_data
       x = linspace (0, 10, 10);
       y = sin (x);
       save mydata x y
     endfunction

   With ‘evalin’, you could write ‘save’ as follows:

     function save (file, name1, name2)
       f = open_save_file (file);
       save_var (f, name1, evalin ("caller", name1));
       save_var (f, name2, evalin ("caller", name2));
     endfunction

Here, ‘caller’ is the ‘create_data’ function and ‘name1’ is the string
"x", which evaluates simply as the value of ‘x’.

   You later want to load the values back from ‘mydata’ in a different
context:

     function process_data
       load mydata
       ... do work ...
     endfunction

With ‘assignin’, you could write ‘load’ as follows:

     function load (file)
       f = open_load_file (file);
       [name, val] = load_var (f);
       assignin ("caller", name, val);
       [name, val] = load_var (f);
       assignin ("caller", name, val);
     endfunction

Here, ‘caller’ is the ‘process_data’ function.

   You can set and use variables at the command prompt using the context
‘base’ rather than ‘caller’.

   These functions are rarely used in practice.  One example is the
‘fail (‘code’, ‘pattern’)’ function which evaluates ‘code’ in the
caller’s context and checks that the error message it produces matches
the given pattern.  Other examples such as ‘save’ and ‘load’ are written
in C++ where all Octave variables are in the ‘caller’ context and
‘evalin’ is not needed.

 -- : evalin (CONTEXT, TRY)
 -- : evalin (CONTEXT, TRY, CATCH)
     Like ‘eval’, except that the expressions are evaluated in the
     context CONTEXT, which may be either "caller" or "base".

     See also: *note eval: XREFeval, *note assignin: XREFassignin.

 -- : assignin (CONTEXT, VARNAME, VALUE)
     Assign VALUE to VARNAME in context CONTEXT, which may be either
     "base" or "caller".

     See also: *note evalin: XREFevalin.


File: octave.info,  Node: Statements,  Next: Functions and Scripts,  Prev: Evaluation,  Up: Top

10 Statements
*************

Statements may be a simple constant expression or a complicated list of
nested loops and conditional statements.

   “Control statements” such as ‘if’, ‘while’, and so on control the
flow of execution in Octave programs.  All the control statements start
with special keywords such as ‘if’ and ‘while’, to distinguish them from
simple expressions.  Many control statements contain other statements;
for example, the ‘if’ statement contains another statement which may or
may not be executed.

   Each control statement has a corresponding “end” statement that marks
the end of the control statement.  For example, the keyword ‘endif’
marks the end of an ‘if’ statement, and ‘endwhile’ marks the end of a
‘while’ statement.  You can use the keyword ‘end’ anywhere a more
specific end keyword is expected, but using the more specific keywords
is preferred because if you use them, Octave is able to provide better
diagnostics for mismatched or missing end tokens.

   The list of statements contained between keywords like ‘if’ or
‘while’ and the corresponding end statement is called the “body” of a
control statement.

* Menu:

* The if Statement::
* The switch Statement::
* The while Statement::
* The do-until Statement::
* The for Statement::
* The break Statement::
* The continue Statement::
* The unwind_protect Statement::
* The try Statement::
* Continuation Lines::


File: octave.info,  Node: The if Statement,  Next: The switch Statement,  Up: Statements

10.1 The if Statement
=====================

The ‘if’ statement is Octave’s decision-making statement.  There are
three basic forms of an ‘if’ statement.  In its simplest form, it looks
like this:

     if (CONDITION)
       THEN-BODY
     endif

CONDITION is an expression that controls what the rest of the statement
will do.  The THEN-BODY is executed only if CONDITION is true.

   The condition in an ‘if’ statement is considered true if its value is
nonzero, and false if its value is zero.  If the value of the
conditional expression in an ‘if’ statement is a vector or a matrix, it
is considered true only if it is non-empty and _all_ of the elements are
nonzero.  The conceptually equivalent code when CONDITION is a matrix is
shown below.

     if (MATRIX) ≡ if (all (MATRIX(:)))

The second form of an if statement looks like this:

     if (CONDITION)
       THEN-BODY
     else
       ELSE-BODY
     endif

If CONDITION is true, THEN-BODY is executed; otherwise, ELSE-BODY is
executed.

   Here is an example:

     if (rem (x, 2) == 0)
       printf ("x is even\n");
     else
       printf ("x is odd\n");
     endif

   In this example, if the expression ‘rem (x, 2) == 0’ is true (that
is, the value of ‘x’ is divisible by 2), then the first ‘printf’
statement is evaluated, otherwise the second ‘printf’ statement is
evaluated.

   The third and most general form of the ‘if’ statement allows multiple
decisions to be combined in a single statement.  It looks like this:

     if (CONDITION)
       THEN-BODY
     elseif (CONDITION)
       ELSEIF-BODY
     else
       ELSE-BODY
     endif

Any number of ‘elseif’ clauses may appear.  Each condition is tested in
turn, and if one is found to be true, its corresponding BODY is
executed.  If none of the conditions are true and the ‘else’ clause is
present, its body is executed.  Only one ‘else’ clause may appear, and
it must be the last part of the statement.

   In the following example, if the first condition is true (that is,
the value of ‘x’ is divisible by 2), then the first ‘printf’ statement
is executed.  If it is false, then the second condition is tested, and
if it is true (that is, the value of ‘x’ is divisible by 3), then the
second ‘printf’ statement is executed.  Otherwise, the third ‘printf’
statement is performed.

     if (rem (x, 2) == 0)
       printf ("x is even\n");
     elseif (rem (x, 3) == 0)
       printf ("x is odd and divisible by 3\n");
     else
       printf ("x is odd\n");
     endif

   Note that the ‘elseif’ keyword must not be spelled ‘else if’, as is
allowed in Fortran.  If it is, the space between the ‘else’ and ‘if’
will tell Octave to treat this as a new ‘if’ statement within another
‘if’ statement’s ‘else’ clause.  For example, if you write

     if (C1)
       BODY-1
     else if (C2)
       BODY-2
     endif

Octave will expect additional input to complete the first ‘if’
statement.  If you are using Octave interactively, it will continue to
prompt you for additional input.  If Octave is reading this input from a
file, it may complain about missing or mismatched ‘end’ statements, or,
if you have not used the more specific ‘end’ statements (‘endif’,
‘endfor’, etc.), it may simply produce incorrect results, without
producing any warning messages.

   It is much easier to see the error if we rewrite the statements above
like this,

     if (C1)
       BODY-1
     else
       if (C2)
         BODY-2
       endif

using the indentation to show how Octave groups the statements.  *Note
Functions and Scripts::.


File: octave.info,  Node: The switch Statement,  Next: The while Statement,  Prev: The if Statement,  Up: Statements

10.2 The switch Statement
=========================

It is very common to take different actions depending on the value of
one variable.  This is possible using the ‘if’ statement in the
following way

     if (X == 1)
       do_something ();
     elseif (X == 2)
       do_something_else ();
     else
       do_something_completely_different ();
     endif

This kind of code can however be very cumbersome to both write and
maintain.  To overcome this problem Octave supports the ‘switch’
statement.  Using this statement, the above example becomes

     switch (X)
       case 1
         do_something ();
       case 2
         do_something_else ();
       otherwise
         do_something_completely_different ();
     endswitch

This code makes the repetitive structure of the problem more explicit,
making the code easier to read, and hence maintain.  Also, if the
variable ‘X’ should change its name, only one line would need changing
compared to one line per case when ‘if’ statements are used.

   The general form of the ‘switch’ statement is

     switch (EXPRESSION)
       case LABEL
         COMMAND_LIST
       case LABEL
         COMMAND_LIST
       ...

       otherwise
         COMMAND_LIST
     endswitch

where LABEL can be any expression.  However, duplicate LABEL values are
not detected, and only the COMMAND_LIST corresponding to the first match
will be executed.  For the ‘switch’ statement to be meaningful at least
one ‘case LABEL COMMAND_LIST’ clause must be present, while the
‘otherwise COMMAND_LIST’ clause is optional.

   If LABEL is a cell array the corresponding COMMAND_LIST is executed
if _any_ of the elements of the cell array match EXPRESSION.  As an
example, the following program will print ‘Variable is either 6 or 7’.

     A = 7;
     switch (A)
       case { 6, 7 }
         printf ("variable is either 6 or 7\n");
       otherwise
         printf ("variable is neither 6 nor 7\n");
     endswitch

   As with all other specific ‘end’ keywords, ‘endswitch’ may be
replaced by ‘end’, but you can get better diagnostics if you use the
specific forms.

   One advantage of using the ‘switch’ statement compared to using ‘if’
statements is that the LABELs can be strings.  If an ‘if’ statement is
used it is _not_ possible to write

     if (X == "a string") # This is NOT valid

since a character-to-character comparison between ‘X’ and the string
will be made instead of evaluating if the strings are equal.  This
special-case is handled by the ‘switch’ statement, and it is possible to
write programs that look like this

     switch (X)
       case "a string"
         do_something
       ...
     endswitch

* Menu:

* Notes for the C Programmer::


File: octave.info,  Node: Notes for the C Programmer,  Up: The switch Statement

10.2.1 Notes for the C Programmer
---------------------------------

The ‘switch’ statement is also available in the widely used C
programming language.  There are, however, some differences between the
statement in Octave and C

   • Cases are exclusive, so they don’t ‘fall through’ as do the cases
     in the ‘switch’ statement of the C language.

   • The COMMAND_LIST elements are not optional.  Making the list
     optional would have meant requiring a separator between the label
     and the command list.  Otherwise, things like

          switch (foo)
            case (1) -2
            ...

     would produce surprising results, as would

          switch (foo)
            case (1)
            case (2)
              doit ();
            ...

     particularly for C programmers.  If ‘doit()’ should be executed if
     FOO is either ‘1’ or ‘2’, the above code should be written with a
     cell array like this

          switch (foo)
            case { 1, 2 }
              doit ();
            ...


File: octave.info,  Node: The while Statement,  Next: The do-until Statement,  Prev: The switch Statement,  Up: Statements

10.3 The while Statement
========================

In programming, a “loop” means a part of a program that is (or at least
can be) executed two or more times in succession.

   The ‘while’ statement is the simplest looping statement in Octave.
It repeatedly executes a statement as long as a condition is true.  As
with the condition in an ‘if’ statement, the condition in a ‘while’
statement is considered true if its value is nonzero, and false if its
value is zero.  If the value of the conditional expression in a ‘while’
statement is a vector or a matrix, it is considered true only if it is
non-empty and _all_ of the elements are nonzero.

   Octave’s ‘while’ statement looks like this:

     while (CONDITION)
       BODY
     endwhile

Here BODY is a statement or list of statements that we call the “body”
of the loop, and CONDITION is an expression that controls how long the
loop keeps running.

   The first thing the ‘while’ statement does is test CONDITION.  If
CONDITION is true, it executes the statement BODY.  After BODY has been
executed, CONDITION is tested again, and if it is still true, BODY is
executed again.  This process repeats until CONDITION is no longer true.
If CONDITION is initially false, the body of the loop is never executed.

   This example creates a variable ‘fib’ that contains the first ten
elements of the Fibonacci sequence.

     fib = ones (1, 10);
     i = 3;
     while (i <= 10)
       fib (i) = fib (i-1) + fib (i-2);
       i++;
     endwhile

Here the body of the loop contains two statements.

   The loop works like this: first, the value of ‘i’ is set to 3.  Then,
the ‘while’ tests whether ‘i’ is less than or equal to 10.  This is the
case when ‘i’ equals 3, so the value of the ‘i’-th element of ‘fib’ is
set to the sum of the previous two values in the sequence.  Then the
‘i++’ increments the value of ‘i’ and the loop repeats.  The loop
terminates when ‘i’ reaches 11.

   A newline is not required between the condition and the body; but
using one makes the program clearer unless the body is very simple.


File: octave.info,  Node: The do-until Statement,  Next: The for Statement,  Prev: The while Statement,  Up: Statements

10.4 The do-until Statement
===========================

The ‘do-until’ statement is similar to the ‘while’ statement, except
that it repeatedly executes a statement until a condition becomes true,
and the test of the condition is at the end of the loop, so the body of
the loop is always executed at least once.  As with the condition in an
‘if’ statement, the condition in a ‘do-until’ statement is considered
true if its value is nonzero, and false if its value is zero.  If the
value of the conditional expression in a ‘do-until’ statement is a
vector or a matrix, it is considered true only if it is non-empty and
_all_ of the elements are nonzero.

   Octave’s ‘do-until’ statement looks like this:

     do
       BODY
     until (CONDITION)

Here BODY is a statement or list of statements that we call the “body”
of the loop, and CONDITION is an expression that controls how long the
loop keeps running.

   This example creates a variable ‘fib’ that contains the first ten
elements of the Fibonacci sequence.

     fib = ones (1, 10);
     i = 2;
     do
       i++;
       fib (i) = fib (i-1) + fib (i-2);
     until (i == 10)

   A newline is not required between the ‘do’ keyword and the body; but
using one makes the program clearer unless the body is very simple.


File: octave.info,  Node: The for Statement,  Next: The break Statement,  Prev: The do-until Statement,  Up: Statements

10.5 The for Statement
======================

The ‘for’ statement makes it more convenient to count iterations of a
loop.  The general form of the ‘for’ statement looks like this:

     for VAR = EXPRESSION
       BODY
     endfor

where BODY stands for any statement or list of statements, EXPRESSION is
any valid expression, and VAR may take several forms.  Usually it is a
simple variable name or an indexed variable.  If the value of EXPRESSION
is a structure, VAR may also be a vector with two elements.  *Note
Looping Over Structure Elements::, below.

   The assignment expression in the ‘for’ statement works a bit
differently than Octave’s normal assignment statement.  Instead of
assigning the complete result of the expression, it assigns each column
of the expression to VAR in turn.  If EXPRESSION is a range, a row
vector, or a scalar, the value of VAR will be a scalar each time the
loop body is executed.  If VAR is a column vector or a matrix, VAR will
be a column vector each time the loop body is executed.

   The following example shows another way to create a vector containing
the first ten elements of the Fibonacci sequence, this time using the
‘for’ statement:

     fib = ones (1, 10);
     for i = 3:10
       fib(i) = fib(i-1) + fib(i-2);
     endfor

This code works by first evaluating the expression ‘3:10’, to produce a
range of values from 3 to 10 inclusive.  Then the variable ‘i’ is
assigned the first element of the range and the body of the loop is
executed once.  When the end of the loop body is reached, the next value
in the range is assigned to the variable ‘i’, and the loop body is
executed again.  This process continues until there are no more elements
to assign.

   Within Octave is it also possible to iterate over matrices or cell
arrays using the ‘for’ statement.  For example consider

     disp ("Loop over a matrix")
     for i = [1,3;2,4]
       i
     endfor
     disp ("Loop over a cell array")
     for i = {1,"two";"three",4}
       i
     endfor

In this case the variable ‘i’ takes on the value of the columns of the
matrix or cell matrix.  So the first loop iterates twice, producing two
column vectors ‘[1;2]’, followed by ‘[3;4]’, and likewise for the loop
over the cell array.  This can be extended to loops over
multi-dimensional arrays.  For example:

     a = [1,3;2,4]; c = cat (3, a, 2*a);
     for i = c
       i
     endfor

In the above case, the multi-dimensional matrix C is reshaped to a
two-dimensional matrix as ‘reshape (c, rows (c), prod (size
(c)(2:end)))’ and then the same behavior as a loop over a
two-dimensional matrix is produced.

   Although it is possible to rewrite all ‘for’ loops as ‘while’ loops,
the Octave language has both statements because often a ‘for’ loop is
both less work to type and more natural to think of.  Counting the
number of iterations is very common in loops and it can be easier to
think of this counting as part of looping rather than as something to do
inside the loop.

* Menu:

* Looping Over Structure Elements::


File: octave.info,  Node: Looping Over Structure Elements,  Up: The for Statement

10.5.1 Looping Over Structure Elements
--------------------------------------

A special form of the ‘for’ statement allows you to loop over all the
elements of a structure:

     for [ VAL, KEY ] = EXPRESSION
       BODY
     endfor

In this form of the ‘for’ statement, the value of EXPRESSION must be a
structure.  If it is, KEY and VAL are set to the name of the element and
the corresponding value in turn, until there are no more elements.  For
example:

     x.a = 1
     x.b = [1, 2; 3, 4]
     x.c = "string"
     for [val, key] = x
       key
       val
     endfor

          ⊣ key = a
          ⊣ val = 1
          ⊣ key = b
          ⊣ val =
          ⊣
          ⊣   1  2
          ⊣   3  4
          ⊣
          ⊣ key = c
          ⊣ val = string

   The elements are not accessed in any particular order.  If you need
to cycle through the list in a particular way, you will have to use the
function ‘fieldnames’ and sort the list yourself.


File: octave.info,  Node: The break Statement,  Next: The continue Statement,  Prev: The for Statement,  Up: Statements

10.6 The break Statement
========================

The ‘break’ statement jumps out of the innermost ‘while’, ‘do-until’, or
‘for’ loop that encloses it.  The ‘break’ statement may only be used
within the body of a loop.  The following example finds the smallest
divisor of a given integer, and also identifies prime numbers:

     num = 103;
     div = 2;
     while (div*div <= num)
       if (rem (num, div) == 0)
         break;
       endif
       div++;
     endwhile
     if (rem (num, div) == 0)
       printf ("Smallest divisor of %d is %d\n", num, div)
     else
       printf ("%d is prime\n", num);
     endif

   When the remainder is zero in the first ‘while’ statement, Octave
immediately “breaks out” of the loop.  This means that Octave proceeds
immediately to the statement following the loop and continues
processing.  (This is very different from the ‘exit’ statement which
stops the entire Octave program.)

   Here is another program equivalent to the previous one.  It
illustrates how the CONDITION of a ‘while’ statement could just as well
be replaced with a ‘break’ inside an ‘if’:

     num = 103;
     div = 2;
     while (1)
       if (rem (num, div) == 0)
         printf ("Smallest divisor of %d is %d\n", num, div);
         break;
       endif
       div++;
       if (div*div > num)
         printf ("%d is prime\n", num);
         break;
       endif
     endwhile


File: octave.info,  Node: The continue Statement,  Next: The unwind_protect Statement,  Prev: The break Statement,  Up: Statements

10.7 The continue Statement
===========================

The ‘continue’ statement, like ‘break’, is used only inside ‘while’,
‘do-until’, or ‘for’ loops.  It skips over the rest of the loop body,
causing the next cycle around the loop to begin immediately.  Contrast
this with ‘break’, which jumps out of the loop altogether.  Here is an
example:

     # print elements of a vector of random
     # integers that are even.

     # first, create a row vector of 10 random
     # integers with values between 0 and 100:

     vec = round (rand (1, 10) * 100);

     # print what we're interested in:

     for x = vec
       if (rem (x, 2) != 0)
         continue;
       endif
       printf ("%d\n", x);
     endfor

   If one of the elements of VEC is an odd number, this example skips
the print statement for that element, and continues back to the first
statement in the loop.

   This is not a practical example of the ‘continue’ statement, but it
should give you a clear understanding of how it works.  Normally, one
would probably write the loop like this:

     for x = vec
       if (rem (x, 2) == 0)
         printf ("%d\n", x);
       endif
     endfor


File: octave.info,  Node: The unwind_protect Statement,  Next: The try Statement,  Prev: The continue Statement,  Up: Statements

10.8 The unwind_protect Statement
=================================

Octave supports a limited form of exception handling modeled after the
unwind-protect form of Lisp.

   The general form of an ‘unwind_protect’ block looks like this:

     unwind_protect
       BODY
     unwind_protect_cleanup
       CLEANUP
     end_unwind_protect

where BODY and CLEANUP are both optional and may contain any Octave
expressions or commands.  The statements in CLEANUP are guaranteed to be
executed regardless of how control exits BODY.

   This is useful to protect temporary changes to global variables from
possible errors.  For example, the following code will always restore
the original value of the global variable ‘frobnosticate’ even if an
error occurs in the first part of the ‘unwind_protect’ block.

     save_frobnosticate = frobnosticate;
     unwind_protect
       frobnosticate = true;
       ...
     unwind_protect_cleanup
       frobnosticate = save_frobnosticate;
     end_unwind_protect

Without ‘unwind_protect’, the value of FROBNOSTICATE would not be
restored if an error occurs while evaluating the first part of the
‘unwind_protect’ block because evaluation would stop at the point of the
error and the statement to restore the value would not be executed.

   In addition to unwind_protect, Octave supports another form of
exception handling, the ‘try’ block.


File: octave.info,  Node: The try Statement,  Next: Continuation Lines,  Prev: The unwind_protect Statement,  Up: Statements

10.9 The try Statement
======================

The original form of a ‘try’ block looks like this:

     try
       BODY
     catch
       CLEANUP
     end_try_catch

where BODY and CLEANUP are both optional and may contain any Octave
expressions or commands.  The statements in CLEANUP are only executed if
an error occurs in BODY.

   No warnings or error messages are printed while BODY is executing.
If an error does occur during the execution of BODY, CLEANUP can use the
functions ‘lasterr’ or ‘lasterror’ to access the text of the message
that would have been printed, as well as its identifier.  The
alternative form,

     try
       BODY
     catch ERR
       CLEANUP
     end_try_catch

will automatically store the output of ‘lasterror’ in the structure ERR.
*Note Errors and Warnings::, for more information about the ‘lasterr’
and ‘lasterror’ functions.


File: octave.info,  Node: Continuation Lines,  Prev: The try Statement,  Up: Statements

10.10 Continuation Lines
========================

In the Octave language, most statements end with a newline character and
you must tell Octave to ignore the newline character in order to
continue a statement from one line to the next.  Lines that end with the
characters ‘...’ are joined with the following line before they are
divided into tokens by Octave’s parser.  For example, the lines

     x = long_variable_name ...
         + longer_variable_name ...
         - 42

form a single statement.

   Any text between the continuation marker and the newline character is
ignored.  For example, the statement

     x = long_variable_name ...    # comment one
         + longer_variable_name ...comment two
         - 42                      # last comment

is equivalent to the one shown above.

   Inside double-quoted string constants, the character ‘\’ has to be
used as continuation marker.  The ‘\’ must appear at the end of the line
just before the newline character:

     s = "This text starts in the first line \
     and is continued in the second line."

Input that occurs inside parentheses can be continued to the next line
without having to use a continuation marker.  For example, it is
possible to write statements like

     if (fine_dining_destination == on_a_boat
         || fine_dining_destination == on_a_train)
       seuss (i, will, not, eat, them, sam, i, am, i,
              will, not, eat, green, eggs, and, ham);
     endif

without having to add to the clutter with continuation markers.


File: octave.info,  Node: Functions and Scripts,  Next: Errors and Warnings,  Prev: Statements,  Up: Top

11 Functions and Scripts
************************

Complicated Octave programs can often be simplified by defining
functions.  Functions can be defined directly on the command line during
interactive Octave sessions, or in external files, and can be called
just like built-in functions.

* Menu:

* Introduction to Function and Script Files::
* Defining Functions::
* Multiple Return Values::
* Variable-length Argument Lists::
* Ignoring Arguments::
* Variable-length Return Lists::
* Returning from a Function::
* Default Arguments::
* Function Files::
* Script Files::
* Function Handles Anonymous Functions Inline Functions::
* Commands::
* Organization of Functions::


File: octave.info,  Node: Introduction to Function and Script Files,  Next: Defining Functions,  Up: Functions and Scripts

11.1 Introduction to Function and Script Files
==============================================

There are seven different things covered in this section.
  1. Typing in a function at the command prompt.

  2. Storing a group of commands in a file — called a script file.

  3. Storing a function in a file—called a function file.

  4. Subfunctions in function files.

  5. Multiple functions in one script file.

  6. Private functions.

  7. Nested functions.

   Both function files and script files end with an extension of .m, for
MATLAB compatibility.  If you want more than one independent functions
in a file, it must be a script file (*note Script Files::), and to use
these functions you must execute the script file before you can use the
functions that are in the script file.


File: octave.info,  Node: Defining Functions,  Next: Multiple Return Values,  Prev: Introduction to Function and Script Files,  Up: Functions and Scripts

11.2 Defining Functions
=======================

In its simplest form, the definition of a function named NAME looks like
this:

     function NAME
       BODY
     endfunction

A valid function name is like a valid variable name: a sequence of
letters, digits and underscores, not starting with a digit.  Functions
share the same pool of names as variables.

   The function BODY consists of Octave statements.  It is the most
important part of the definition, because it says what the function
should actually _do_.

   For example, here is a function that, when executed, will ring the
bell on your terminal (assuming that it is possible to do so):

     function wakeup
       printf ("\a");
     endfunction

   The ‘printf’ statement (*note Input and Output::) simply tells Octave
to print the string "\a".  The special character ‘\a’ stands for the
alert character (ASCII 7).  *Note Strings::.

   Once this function is defined, you can ask Octave to evaluate it by
typing the name of the function.

   Normally, you will want to pass some information to the functions you
define.  The syntax for passing parameters to a function in Octave is

     function NAME (ARG-LIST)
       BODY
     endfunction

where ARG-LIST is a comma-separated list of the function’s arguments.
When the function is called, the argument names are used to hold the
argument values given in the call.  The list of arguments may be empty,
in which case this form is equivalent to the one shown above.

   To print a message along with ringing the bell, you might modify the
‘wakeup’ to look like this:

     function wakeup (message)
       printf ("\a%s\n", message);
     endfunction

   Calling this function using a statement like this

     wakeup ("Rise and shine!");

will cause Octave to ring your terminal’s bell and print the message
‘Rise and shine!’, followed by a newline character (the ‘\n’ in the
first argument to the ‘printf’ statement).

   In most cases, you will also want to get some information back from
the functions you define.  Here is the syntax for writing a function
that returns a single value:

     function RET-VAR = NAME (ARG-LIST)
       BODY
     endfunction

The symbol RET-VAR is the name of the variable that will hold the value
to be returned by the function.  This variable must be defined before
the end of the function body in order for the function to return a
value.

   Variables used in the body of a function are local to the function.
Variables named in ARG-LIST and RET-VAR are also local to the function.
*Note Global Variables::, for information about how to access global
variables inside a function.

   For example, here is a function that computes the average of the
elements of a vector:

     function retval = avg (v)
       retval = sum (v) / length (v);
     endfunction

   If we had written ‘avg’ like this instead,

     function retval = avg (v)
       if (isvector (v))
         retval = sum (v) / length (v);
       endif
     endfunction

and then called the function with a matrix instead of a vector as the
argument, Octave would have printed an error message like this:

     error: value on right hand side of assignment is undefined

because the body of the ‘if’ statement was never executed, and ‘retval’
was never defined.  To prevent obscure errors like this, it is a good
idea to always make sure that the return variables will always have
values, and to produce meaningful error messages when problems are
encountered.  For example, ‘avg’ could have been written like this:

     function retval = avg (v)
       retval = 0;
       if (isvector (v))
         retval = sum (v) / length (v);
       else
         error ("avg: expecting vector argument");
       endif
     endfunction

   There is still one additional problem with this function.  What if it
is called without an argument?  Without additional error checking,
Octave will probably print an error message that won’t really help you
track down the source of the error.  To allow you to catch errors like
this, Octave provides each function with an automatic variable called
‘nargin’.  Each time a function is called, ‘nargin’ is automatically
initialized to the number of arguments that have actually been passed to
the function.  For example, we might rewrite the ‘avg’ function like
this:

     function retval = avg (v)
       retval = 0;
       if (nargin != 1)
         usage ("avg (vector)");
       endif
       if (isvector (v))
         retval = sum (v) / length (v);
       else
         error ("avg: expecting vector argument");
       endif
     endfunction

   Although Octave does not automatically report an error if you call a
function with more arguments than expected, doing so probably indicates
that something is wrong.  Octave also does not automatically report an
error if a function is called with too few arguments, but any attempt to
use a variable that has not been given a value will result in an error.
To avoid such problems and to provide useful messages, we check for both
possibilities and issue our own error message.

 -- : nargin ()
 -- : nargin (FCN)
     Report the number of input arguments to a function.

     Called from within a function, return the number of arguments
     passed to the function.  At the top level, return the number of
     command line arguments passed to Octave.

     If called with the optional argument FCN—a function name or
     handle—return the declared number of arguments that the function
     can accept.

     If the last argument to FCN is VARARGIN the returned value is
     negative.  For example, the function ‘union’ for sets is declared
     as

          function [y, ia, ib] = union (a, b, varargin)

          and

          nargin ("union")
          ⇒ -3

     Programming Note: ‘nargin’ does not work on compiled functions
     (‘.oct’ files) such as built-in or dynamically loaded functions.

     See also: *note nargout: XREFnargout, *note narginchk:
     XREFnarginchk, *note varargin: XREFvarargin, *note inputname:
     XREFinputname.

 -- : inputname (N)
     Return the name of the N-th argument to the calling function.

     If the argument is not a simple variable name, return an empty
     string.  As an example, a reference to a field in a structure such
     as ‘s.field’ is not a simple name and will return "".

     ‘inputname’ is only useful within a function.  When used at the
     command line it always returns an empty string.

     See also: *note nargin: XREFnargin, *note nthargout: XREFnthargout.

 -- : VAL = silent_functions ()
 -- : OLD_VAL = silent_functions (NEW_VAL)
 -- : silent_functions (NEW_VAL, "local")
     Query or set the internal variable that controls whether internal
     output from a function is suppressed.

     If this option is disabled, Octave will display the results
     produced by evaluating expressions within a function body that are
     not terminated with a semicolon.

     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.


File: octave.info,  Node: Multiple Return Values,  Next: Variable-length Argument Lists,  Prev: Defining Functions,  Up: Functions and Scripts

11.3 Multiple Return Values
===========================

Unlike many other computer languages, Octave allows you to define
functions that return more than one value.  The syntax for defining
functions that return multiple values is

     function [RET-LIST] = NAME (ARG-LIST)
       BODY
     endfunction

where NAME, ARG-LIST, and BODY have the same meaning as before, and
RET-LIST is a comma-separated list of variable names that will hold the
values returned from the function.  The list of return values must have
at least one element.  If RET-LIST has only one element, this form of
the ‘function’ statement is equivalent to the form described in the
previous section.

   Here is an example of a function that returns two values, the maximum
element of a vector and the index of its first occurrence in the vector.

     function [max, idx] = vmax (v)
       idx = 1;
       max = v (idx);
       for i = 2:length (v)
         if (v (i) > max)
           max = v (i);
           idx = i;
         endif
       endfor
     endfunction

   In this particular case, the two values could have been returned as
elements of a single array, but that is not always possible or
convenient.  The values to be returned may not have compatible
dimensions, and it is often desirable to give the individual return
values distinct names.

   It is possible to use the ‘nthargout’ function to obtain only some of
the return values or several at once in a cell array.  *Note Cell Array
Objects::.

 -- : nthargout (N, FUNC, ...)
 -- : nthargout (N, NTOT, FUNC, ...)
     Return the Nth output argument of the function specified by the
     function handle or string FUNC.

     Any additional arguments are passed directly to FUNC.  The total
     number of arguments to call FUNC with can be passed in NTOT; by
     default NTOT is N.  The input N can also be a vector of indices of
     the output, in which case the output will be a cell array of the
     requested output arguments.

     The intended use ‘nthargout’ is to avoid intermediate variables.
     For example, when finding the indices of the maximum entry of a
     matrix, the following two compositions of nthargout

          M = magic (5);
          cell2mat (nthargout ([1, 2], @ind2sub, size (M),
                               nthargout (2, @max, M(:))))
          ⇒ 5   3

     are completely equivalent to the following lines:

          M = magic (5);
          [~, idx] = max (M(:));
          [i, j] = ind2sub (size (M), idx);
          [i, j]
          ⇒ 5   3

     It can also be helpful to have all output arguments in a single
     cell in the following manner:

          USV = nthargout ([1:3], @svd, hilb (5));

     See also: *note nargin: XREFnargin, *note nargout: XREFnargout,
     *note varargin: XREFvarargin, *note varargout: XREFvarargout, *note
     isargout: XREFisargout.

   In addition to setting ‘nargin’ each time a function is called,
Octave also automatically initializes ‘nargout’ to the number of values
that are expected to be returned.  This allows you to write functions
that behave differently depending on the number of values that the user
of the function has requested.  The implicit assignment to the built-in
variable ‘ans’ does not figure in the count of output arguments, so the
value of ‘nargout’ may be zero.

   The ‘svd’ and ‘lu’ functions are examples of built-in functions that
behave differently depending on the value of ‘nargout’.

   It is possible to write functions that only set some return values.
For example, calling the function

     function [x, y, z] = f ()
       x = 1;
       z = 2;
     endfunction

as

     [a, b, c] = f ()

produces:

     a = 1

     b = [](0x0)

     c = 2

along with a warning.

 -- : nargout ()
 -- : nargout (FCN)
     Report the number of output arguments from a function.

     Called from within a function, return the number of values the
     caller expects to receive.  At the top level, ‘nargout’ with no
     argument is undefined and will produce an error.

     If called with the optional argument FCN—a function name or
     handle—return the number of declared output values that the
     function can produce.

     If the final output argument is VARARGOUT the returned value is
     negative.

     For example,

          f ()

     will cause ‘nargout’ to return 0 inside the function ‘f’ and

          [s, t] = f ()

     will cause ‘nargout’ to return 2 inside the function ‘f’.

     In the second usage,

          nargout (@histc)   # or nargout ("histc") using a string input

     will return 2, because ‘histc’ has two outputs, whereas

          nargout (@imread)

     will return -2, because ‘imread’ has two outputs and the second is
     VARARGOUT.

     Programming Note.  ‘nargout’ does not work for built-in functions
     and returns -1 for all anonymous functions.

     See also: *note nargin: XREFnargin, *note varargout: XREFvarargout,
     *note isargout: XREFisargout, *note nthargout: XREFnthargout.

   It is good practice at the head of a function to verify that it has
been called correctly.  In Octave the following idiom is seen frequently

     if (nargin < min_#_inputs || nargin > max_#_inputs)
       print_usage ();
     endif

which stops the function execution and prints a message about the
correct way to call the function whenever the number of inputs is wrong.

   For compatibility with MATLAB, ‘narginchk’ and ‘nargoutchk’ are
available which provide similar error checking.

 -- : narginchk (MINARGS, MAXARGS)
     Check for correct number of input arguments.

     Generate an error message if the number of arguments in the calling
     function is outside the range MINARGS and MAXARGS.  Otherwise, do
     nothing.

     Both MINARGS and MAXARGS must be scalar numeric values.  Zero, Inf,
     and negative values are all allowed, and MINARGS and MAXARGS may be
     equal.

     Note that this function evaluates ‘nargin’ on the caller.

     See also: *note nargoutchk: XREFnargoutchk, *note error: XREFerror,
     *note nargout: XREFnargout, *note nargin: XREFnargin.

 -- : nargoutchk (MINARGS, MAXARGS)
 -- : MSGSTR = nargoutchk (MINARGS, MAXARGS, NARGS)
 -- : MSGSTR = nargoutchk (MINARGS, MAXARGS, NARGS, "string")
 -- : MSGSTRUCT = nargoutchk (MINARGS, MAXARGS, NARGS, "struct")
     Check for correct number of output arguments.

     In the first form, return an error if the number of arguments is
     not between MINARGS and MAXARGS.  Otherwise, do nothing.  Note that
     this function evaluates the value of ‘nargout’ on the caller so its
     value must have not been tampered with.

     Both MINARGS and MAXARGS must be numeric scalars.  Zero, Inf, and
     negative are all valid, and they can have the same value.

     For backwards compatibility, the other forms return an appropriate
     error message string (or structure) if the number of outputs
     requested is invalid.

     This is useful for checking to that the number of output arguments
     supplied to a function is within an acceptable range.

     See also: *note narginchk: XREFnarginchk, *note error: XREFerror,
     *note nargout: XREFnargout, *note nargin: XREFnargin.

   Besides the number of arguments, inputs can be checked for various
properties.  ‘validatestring’ is used for string arguments and
‘validateattributes’ for numeric arguments.

 -- : VALIDSTR = validatestring (STR, STRARRAY)
 -- : VALIDSTR = validatestring (STR, STRARRAY, FUNCNAME)
 -- : VALIDSTR = validatestring (STR, STRARRAY, FUNCNAME, VARNAME)
 -- : VALIDSTR = validatestring (..., POSITION)
     Verify that STR is an element, or substring of an element, in
     STRARRAY.

     When STR is a character string to be tested, and STRARRAY is a
     cellstr of valid values, then VALIDSTR will be the validated form
     of STR where validation is defined as STR being a member or
     substring of VALIDSTR.  This is useful for both verifying and
     expanding short options, such as "r", to their longer forms, such
     as "red".  If STR is a substring of VALIDSTR, and there are
     multiple matches, the shortest match will be returned if all
     matches are substrings of each other.  Otherwise, an error will be
     raised because the expansion of STR is ambiguous.  All comparisons
     are case insensitive.

     The additional inputs FUNCNAME, VARNAME, and POSITION are optional
     and will make any generated validation error message more specific.

     Examples:

          validatestring ("r", {"red", "green", "blue"})
          ⇒ "red"

          validatestring ("b", {"red", "green", "blue", "black"})
          ⇒ error: validatestring: multiple unique matches were found for 'b':
             blue, black

     See also: *note strcmp: XREFstrcmp, *note strcmpi: XREFstrcmpi,
     *note validateattributes: XREFvalidateattributes, *note
     inputParser: XREFinputParser.

 -- : validateattributes (A, CLASSES, ATTRIBUTES)
 -- : validateattributes (A, CLASSES, ATTRIBUTES, ARG_IDX)
 -- : validateattributes (A, CLASSES, ATTRIBUTES, FUNC_NAME)
 -- : validateattributes (A, CLASSES, ATTRIBUTES, FUNC_NAME, ARG_NAME)
 -- : validateattributes (A, CLASSES, ATTRIBUTES, FUNC_NAME, ARG_NAME,
          ARG_IDX)
     Check validity of input argument.

     Confirms that the argument A is valid by belonging to one of
     CLASSES, and holding all of the ATTRIBUTES.  If it does not, an
     error is thrown, with a message formatted accordingly.  The error
     message can be made further complete by the function name FUN_NAME,
     the argument name ARG_NAME, and its position in the input ARG_IDX.

     CLASSES must be a cell array of strings (an empty cell array is
     allowed) with the name of classes (remember that a class name is
     case sensitive).  In addition to the class name, the following
     categories names are also valid:

     "float"
          Floating point value comprising classes "double" and "single".

     "integer"
          Integer value comprising classes (u)int8, (u)int16, (u)int32,
          (u)int64.

     "numeric"
          Numeric value comprising either a floating point or integer
          value.

     ATTRIBUTES must be a cell array with names of checks for A.  Some
     of them require an additional value to be supplied right after the
     name (see details for each below).

     "<="
          All values are less than or equal to the following value in
          ATTRIBUTES.

     "<"
          All values are less than the following value in ATTRIBUTES.

     ">="
          All values are greater than or equal to the following value in
          ATTRIBUTES.

     ">"
          All values are greater than the following value in ATTRIBUTES.

     "2d"
          A 2-dimensional matrix.  Note that vectors and empty matrices
          have 2 dimensions, one of them being of length 1, or both
          length 0.

     "3d"
          Has no more than 3 dimensions.  A 2-dimensional matrix is a
          3-D matrix whose 3rd dimension is of length 1.

     "binary"
          All values are either 1 or 0.

     "column"
          Values are arranged in a single column.

     "decreasing"
          No value is NAN, and each is less than the preceding one.

     "diag"
          Value is a diagonal matrix.

     "even"
          All values are even numbers.

     "finite"
          All values are finite.

     "increasing"
          No value is NAN, and each is greater than the preceding one.

     "integer"
          All values are integer.  This is different than using
          ‘isinteger’ which only checks its an integer type.  This
          checks that each value in A is an integer value, i.e., it has
          no decimal part.

     "ncols"
          Has exactly as many columns as the next value in ATTRIBUTES.

     "ndims"
          Has exactly as many dimensions as the next value in
          ATTRIBUTES.

     "nondecreasing"
          No value is NAN, and each is greater than or equal to the
          preceding one.

     "nonempty"
          It is not empty.

     "nonincreasing"
          No value is NAN, and each is less than or equal to the
          preceding one.

     "nonnan"
          No value is a ‘NaN’.

     "nonnegative"
          All values are non negative.

     "nonsparse"
          It is not a sparse matrix.

     "nonzero"
          No value is zero.

     "nrows"
          Has exactly as many rows as the next value in ATTRIBUTES.

     "numel"
          Has exactly as many elements as the next value in ATTRIBUTES.

     "odd"
          All values are odd numbers.

     "positive"
          All values are positive.

     "real"
          It is a non-complex matrix.

     "row"
          Values are arranged in a single row.

     "scalar"
          It is a scalar.

     "size"
          Its size has length equal to the values of the next in
          ATTRIBUTES.  The next value must is an array with the length
          for each dimension.  To ignore the check for a certain
          dimension, the value of ‘NaN’ can be used.

     "square"
          Is a square matrix.

     "vector"
          Values are arranged in a single vector (column or vector).

     See also: *note isa: XREFisa, *note validatestring:
     XREFvalidatestring, *note inputParser: XREFinputParser.

   If none of the preceding functions is sufficient there is also the
class ‘inputParser’ which can perform extremely complex input checking
for functions.

 -- : P = inputParser ()
     Create object P of the inputParser class.

     This class is designed to allow easy parsing of function arguments.
     The class supports four types of arguments:

       1. mandatory (see ‘addRequired’);

       2. optional (see ‘addOptional’);

       3. named (see ‘addParameter’);

       4. switch (see ‘addSwitch’).

     After defining the function API with these methods, the supplied
     arguments can be parsed with the ‘parse’ method and the parsing
     results accessed with the ‘Results’ accessor.

 -- : inputParser.Parameters
     Return list of parameter names already defined.

 -- : inputParser.Results
     Return structure with argument names as fieldnames and
     corresponding values.

 -- : inputParser.Unmatched
     Return structure similar to ‘Results’, but for unmatched
     parameters.  See the ‘KeepUnmatched’ property.

 -- : inputParser.UsingDefaults
     Return cell array with the names of arguments that are using
     default values.

 -- : inputParser.CaseSensitive = BOOLEAN
     Set whether matching of argument names should be case sensitive.
     Defaults to false.

 -- : inputParser.FunctionName = NAME
     Set function name to be used in error messages; Defaults to empty
     string.

 -- : inputParser.KeepUnmatched = BOOLEAN
     Set whether an error should be given for non-defined arguments.
     Defaults to false.  If set to true, the extra arguments can be
     accessed through ‘Unmatched’ after the ‘parse’ method.  Note that
     since ‘Switch’ and ‘Parameter’ arguments can be mixed, it is not
     possible to know the unmatched type.  If argument is found
     unmatched it is assumed to be of the ‘Parameter’ type and it is
     expected to be followed by a value.

 -- : inputParser.StructExpand = BOOLEAN
     Set whether a structure can be passed to the function instead of
     parameter/value pairs.  Defaults to true.

     The following example shows how to use this class:

          function check (varargin)
            p = inputParser ();                      # create object
            p.FunctionName = "check";                # set function name
            p.addRequired ("pack", @ischar);         # mandatory argument
            p.addOptional ("path", pwd(), @ischar);  # optional argument

            ## create a function handle to anonymous functions for validators
            val_mat = @(x) isvector (x) && all (x <= 1) && all (x >= 0);
            p.addOptional ("mat", [0 0], val_mat);

            ## create two arguments of type "Parameter"
            val_type = @(x) any (strcmp (x, {"linear", "quadratic"}));
            p.addParameter ("type", "linear", val_type);
            val_verb = @(x) any (strcmp (x, {"low", "medium", "high"}));
            p.addParameter ("tolerance", "low", val_verb);

            ## create a switch type of argument
            p.addSwitch ("verbose");

            p.parse (varargin{:});  # Run created parser on inputs

            ## the rest of the function can access inputs by using p.Results.
            ## for example, get the tolerance input with p.Results.tolerance
          endfunction

          check ("mech");           # valid, use defaults for other arguments
          check ();                 # error, one argument is mandatory
          check (1);                # error, since ! ischar
          check ("mech", "~/dev");  # valid, use defaults for other arguments

          check ("mech", "~/dev", [0 1 0 0], "type", "linear");  # valid

          ## following is also valid.  Note how the Switch argument type can
          ## be mixed into or before the Parameter argument type (but it
          ## must still appear after any Optional argument).
          check ("mech", "~/dev", [0 1 0 0], "verbose", "tolerance", "high");

          ## following returns an error since not all optional arguments,
          ## `path' and `mat', were given before the named argument `type'.
          check ("mech", "~/dev", "type", "linear");

     _Note 1_: A function can have any mixture of the four API types but
     they must appear in a specific order.  ‘Required’ arguments must be
     first and can be followed by any ‘Optional’ arguments.  Only the
     ‘Parameter’ and ‘Switch’ arguments may be mixed together and they
     must appear at the end.

     _Note 2_: If both ‘Optional’ and ‘Parameter’ arguments are mixed in
     a function API then once a string Optional argument fails to
     validate it will be considered the end of the ‘Optional’ arguments.
     The remaining arguments will be compared against any ‘Parameter’ or
     ‘Switch’ arguments.

     See also: *note nargin: XREFnargin, *note validateattributes:
     XREFvalidateattributes, *note validatestring: XREFvalidatestring,
     *note varargin: XREFvarargin.


File: octave.info,  Node: Variable-length Argument Lists,  Next: Ignoring Arguments,  Prev: Multiple Return Values,  Up: Functions and Scripts

11.4 Variable-length Argument Lists
===================================

Sometimes the number of input arguments is not known when the function
is defined.  As an example think of a function that returns the smallest
of all its input arguments.  For example:

     a = smallest (1, 2, 3);
     b = smallest (1, 2, 3, 4);

In this example both ‘a’ and ‘b’ would be 1.  One way to write the
‘smallest’ function is

     function val = smallest (arg1, arg2, arg3, arg4, arg5)
       BODY
     endfunction

and then use the value of ‘nargin’ to determine which of the input
arguments should be considered.  The problem with this approach is that
it can only handle a limited number of input arguments.

   If the special parameter name ‘varargin’ appears at the end of a
function parameter list it indicates that the function takes a variable
number of input arguments.  Using ‘varargin’ the function looks like
this

     function val = smallest (varargin)
       BODY
     endfunction

In the function body the input arguments can be accessed through the
variable ‘varargin’.  This variable is a cell array containing all the
input arguments.  *Note Cell Arrays::, for details on working with cell
arrays.  The ‘smallest’ function can now be defined like this

     function val = smallest (varargin)
       val = min ([varargin{:}]);
     endfunction

This implementation handles any number of input arguments, but it’s also
a very simple solution to the problem.

   A slightly more complex example of ‘varargin’ is a function
‘print_arguments’ that prints all input arguments.  Such a function can
be defined like this

     function print_arguments (varargin)
       for i = 1:length (varargin)
         printf ("Input argument %d: ", i);
         disp (varargin{i});
       endfor
     endfunction

This function produces output like this

     print_arguments (1, "two", 3);
          ⊣ Input argument 1:  1
          ⊣ Input argument 2: two
          ⊣ Input argument 3:  3

 -- : [REG, PROP] = parseparams (PARAMS)
 -- : [REG, VAR1, ...] = parseparams (PARAMS, NAME1, DEFAULT1, ...)
     Return in REG the cell elements of PARAM up to the first string
     element and in PROP all remaining elements beginning with the first
     string element.

     For example:

          [reg, prop] = parseparams ({1, 2, "linewidth", 10})
          reg =
          {
            [1,1] = 1
            [1,2] = 2
          }
          prop =
          {
            [1,1] = linewidth
            [1,2] = 10
          }

     The parseparams function may be used to separate regular numeric
     arguments from additional arguments given as property/value pairs
     of the VARARGIN cell array.

     In the second form of the call, available options are specified
     directly with their default values given as name-value pairs.  If
     PARAMS do not form name-value pairs, or if an option occurs that
     does not match any of the available options, an error occurs.

     When called from an m-file function, the error is prefixed with the
     name of the caller function.

     The matching of options is case-insensitive.

     See also: *note varargin: XREFvarargin, *note inputParser:
     XREFinputParser.


File: octave.info,  Node: Ignoring Arguments,  Next: Variable-length Return Lists,  Prev: Variable-length Argument Lists,  Up: Functions and Scripts

11.5 Ignoring Arguments
=======================

In the formal argument list, it is possible to use the dummy placeholder
‘~’ instead of a name.  This indicates that the corresponding argument
value should be ignored and not stored to any variable.

     function val = pick2nd (~, arg2)
       val = arg2;
     endfunction

   The value of ‘nargin’ is not affected by using this declaration.

   Return arguments can also be ignored using the same syntax.  For
example, the sort function returns both the sorted values, and an index
vector for the original input which will result in a sorted output.
Ignoring the second output is simple—don’t request more than one output.
But ignoring the first, and calculating just the second output, requires
the use of the ‘~’ placeholder.

     x = [2, 3, 1];
     [s, i] = sort (x)
     ⇒
     s =

        1   2   3

     i =

        3   1   2

     [~, i] = sort (x)
     ⇒
     i =

        3   1   2

   When using the ‘~’ placeholder, commas—not whitespace—must be used to
separate output arguments.  Otherwise, the interpreter will view ‘~’ as
the logical not operator.

     [~ i] = sort (x)
     parse error:

       invalid left hand side of assignment

   Functions may take advantage of ignored outputs to reduce the number
of calculations performed.  To do so, use the ‘isargout’ function to
query whether the output argument is wanted.  For example:

     function [out1, out2] = long_function (x, y, z)
       if (isargout (1))
         ## Long calculation
         ...
         out1 = result;
       endif
       ...
     endfunction

 -- : isargout (K)
     Within a function, return a logical value indicating whether the
     argument K will be assigned to a variable on output.

     If the result is false, the argument has been ignored during the
     function call through the use of the tilde (~) special output
     argument.  Functions can use ‘isargout’ to avoid performing
     unnecessary calculations for outputs which are unwanted.

     If K is outside the range ‘1:max (nargout)’, the function returns
     false.  K can also be an array, in which case the function works
     element-by-element and a logical array is returned.  At the top
     level, ‘isargout’ returns an error.

     See also: *note nargout: XREFnargout, *note varargout:
     XREFvarargout, *note nthargout: XREFnthargout.


File: octave.info,  Node: Variable-length Return Lists,  Next: Returning from a Function,  Prev: Ignoring Arguments,  Up: Functions and Scripts

11.6 Variable-length Return Lists
=================================

It is possible to return a variable number of output arguments from a
function using a syntax that’s similar to the one used with the special
‘varargin’ parameter name.  To let a function return a variable number
of output arguments the special output parameter name ‘varargout’ is
used.  As with ‘varargin’, ‘varargout’ is a cell array that will contain
the requested output arguments.

   As an example the following function sets the first output argument
to 1, the second to 2, and so on.

     function varargout = one_to_n ()
       for i = 1:nargout
         varargout{i} = i;
       endfor
     endfunction

When called this function returns values like this

     [a, b, c] = one_to_n ()
          ⇒ a =  1
          ⇒ b =  2
          ⇒ c =  3

   If ‘varargin’ (‘varargout’) does not appear as the last element of
the input (output) parameter list, then it is not special, and is
handled the same as any other parameter name.

 -- : [R1, R2, ..., RN] = deal (A)
 -- : [R1, R2, ..., RN] = deal (A1, A2, ..., AN)

     Copy the input parameters into the corresponding output parameters.

     If only a single input parameter is supplied, its value is copied
     to each of the outputs.

     For example,

          [a, b, c] = deal (x, y, z);

     is equivalent to

          a = x;
          b = y;
          c = z;

     and

          [a, b, c] = deal (x);

     is equivalent to

          a = b = c = x;

     Programming Note: ‘deal’ is often used with comma separated lists
     derived from cell arrays or structures.  This is unnecessary as the
     interpreter can perform the same action without the overhead of a
     function call.  For example:

          c = {[1 2], "Three", 4};
          [x, y, z] = c{:}
          ⇒
             x =

                1   2

             y = Three
             z =  4

     See also: *note cell2struct: XREFcell2struct, *note struct2cell:
     XREFstruct2cell, *note repmat: XREFrepmat.


File: octave.info,  Node: Returning from a Function,  Next: Default Arguments,  Prev: Variable-length Return Lists,  Up: Functions and Scripts

11.7 Returning from a Function
==============================

The body of a user-defined function can contain a ‘return’ statement.
This statement returns control to the rest of the Octave program.  It
looks like this:

     return

   Unlike the ‘return’ statement in C, Octave’s ‘return’ statement
cannot be used to return a value from a function.  Instead, you must
assign values to the list of return variables that are part of the
‘function’ statement.  The ‘return’ statement simply makes it easier to
exit a function from a deeply nested loop or conditional statement.

   Here is an example of a function that checks to see if any elements
of a vector are nonzero.

     function retval = any_nonzero (v)
       retval = 0;
       for i = 1:length (v)
         if (v (i) != 0)
           retval = 1;
           return;
         endif
       endfor
       printf ("no nonzero elements found\n");
     endfunction

   Note that this function could not have been written using the ‘break’
statement to exit the loop once a nonzero value is found without adding
extra logic to avoid printing the message if the vector does contain a
nonzero element.

 -- : return
     When Octave encounters the keyword ‘return’ inside a function or
     script, it returns control to the caller immediately.  At the top
     level, the return statement is ignored.  A ‘return’ statement is
     assumed at the end of every function definition.


File: octave.info,  Node: Default Arguments,  Next: Function Files,  Prev: Returning from a Function,  Up: Functions and Scripts

11.8 Default Arguments
======================

Since Octave supports variable number of input arguments, it is very
useful to assign default values to some input arguments.  When an input
argument is declared in the argument list it is possible to assign a
default value to the argument like this

     function NAME (ARG1 = VAL1, ...)
       BODY
     endfunction

If no value is assigned to ARG1 by the user, it will have the value
VAL1.

   As an example, the following function implements a variant of the
classic “Hello, World” program.

     function hello (who = "World")
       printf ("Hello, %s!\n", who);
     endfunction

When called without an input argument the function prints the following

     hello ();
          ⊣ Hello, World!

and when it’s called with an input argument it prints the following

     hello ("Beautiful World of Free Software");
          ⊣ Hello, Beautiful World of Free Software!

   Sometimes it is useful to explicitly tell Octave to use the default
value of an input argument.  This can be done writing a ‘:’ as the value
of the input argument when calling the function.

     hello (:);
          ⊣ Hello, World!


File: octave.info,  Node: Function Files,  Next: Script Files,  Prev: Default Arguments,  Up: Functions and Scripts

11.9 Function Files
===================

Except for simple one-shot programs, it is not practical to have to
define all the functions you need each time you need them.  Instead, you
will normally want to save them in a file so that you can easily edit
them, and save them for use at a later time.

   Octave does not require you to load function definitions from files
before using them.  You simply need to put the function definitions in a
place where Octave can find them.

   When Octave encounters an identifier that is undefined, it first
looks for variables or functions that are already compiled and currently
listed in its symbol table.  If it fails to find a definition there, it
searches a list of directories (the “path”) for files ending in ‘.m’
that have the same base name as the undefined identifier.(1)  Once
Octave finds a file with a name that matches, the contents of the file
are read.  If it defines a _single_ function, it is compiled and
executed.  *Note Script Files::, for more information about how you can
define more than one function in a single file.

   When Octave defines a function from a function file, it saves the
full name of the file it read and the time stamp on the file.  If the
time stamp on the file changes, Octave may reload the file.  When Octave
is running interactively, time stamp checking normally happens at most
once each time Octave prints the prompt.  Searching for new function
definitions also occurs if the current working directory changes.

   Checking the time stamp allows you to edit the definition of a
function while Octave is running, and automatically use the new function
definition without having to restart your Octave session.

   To avoid degrading performance unnecessarily by checking the time
stamps on functions that are not likely to change, Octave assumes that
function files in the directory tree
‘OCTAVE-HOME/share/octave/VERSION/m’ will not change, so it doesn’t have
to check their time stamps every time the functions defined in those
files are used.  This is normally a very good assumption and provides a
significant improvement in performance for the function files that are
distributed with Octave.

   If you know that your own function files will not change while you
are running Octave, you can improve performance by calling
‘ignore_function_time_stamp ("all")’, so that Octave will ignore the
time stamps for all function files.  Passing "system" to this function
resets the default behavior.

 -- : edit NAME
 -- : edit FIELD VALUE
 -- : VALUE = edit ("get", FIELD)
 -- : VALUE = edit ("get", "all")
     Edit the named function, or change editor settings.

     If ‘edit’ is called with the name of a file or function as its
     argument it will be opened in the text editor defined by ‘EDITOR’.

        • If the function NAME is available in a file on your path and
          that file is modifiable, then it will be edited in place.  If
          it is a system function, then it will first be copied to the
          directory ‘HOME’ (see below) and then edited.  If no file is
          found, then the m-file variant, ending with ".m", will be
          considered.  If still no file is found, then variants with a
          leading "@" and then with both a leading "@" and trailing ".m"
          will be considered.

        • If NAME is the name of a function defined in the interpreter
          but not in an m-file, then an m-file will be created in ‘HOME’
          to contain that function along with its current definition.

        • If ‘NAME.cc’ is specified, then it will search for ‘NAME.cc’
          in the path and try to modify it, otherwise it will create a
          new ‘.cc’ file in the current directory.  If NAME happens to
          be an m-file or interpreter defined function, then the text of
          that function will be inserted into the .cc file as a comment.

        • If ‘NAME.ext’ is on your path then it will be edited,
          otherwise the editor will be started with ‘NAME.ext’ in the
          current directory as the filename.  If ‘NAME.ext’ is not
          modifiable, it will be copied to ‘HOME’ before editing.

          *Warning:* You may need to clear NAME before the new
          definition is available.  If you are editing a .cc file, you
          will need to execute ‘mkoctfile NAME.cc’ before the definition
          will be available.

     If ‘edit’ is called with FIELD and VALUE variables, the value of
     the control field FIELD will be set to VALUE.

     If an output argument is requested and the first input argument is
     ‘get’ then ‘edit’ will return the value of the control field FIELD.
     If the control field does not exist, edit will return a structure
     containing all fields and values.  Thus, ‘edit ("get", "all")’
     returns a complete control structure.

     The following control fields are used:

     ‘home’
          This is the location of user local m-files.  Be sure it is in
          your path.  The default is ‘~/octave’.

     ‘author’
          This is the name to put after the "## Author:" field of new
          functions.  By default it guesses from the ‘gecos’ field of
          the password database.

     ‘email’
          This is the e-mail address to list after the name in the
          author field.  By default it guesses ‘<$LOGNAME@$HOSTNAME>’,
          and if ‘$HOSTNAME’ is not defined it uses ‘uname -n’.  You
          probably want to override this.  Be sure to use the format
          ‘<user@host>’.

     ‘license’

          ‘gpl’
               GNU General Public License (default).

          ‘bsd’
               BSD-style license without advertising clause.

          ‘pd’
               Public domain.

          ‘"text"’
               Your own default copyright and license.

          Unless you specify ‘pd’, edit will prepend the copyright
          statement with "Copyright (C) YYYY Author".

     ‘mode’
          This value determines whether the editor should be started in
          async mode (editor is started in the background and Octave
          continues) or sync mode (Octave waits until the editor exits).
          Set it to "sync" to start the editor in sync mode.  The
          default is "async" (*note system: XREFsystem.).

     ‘editinplace’
          Determines whether files should be edited in place, without
          regard to whether they are modifiable or not.  The default is
          ‘false’.

 -- : mfilename ()
 -- : mfilename ("fullpath")
 -- : mfilename ("fullpathext")
     Return the name of the currently executing file.

     When called from outside an m-file return the empty string.

     Given the argument "fullpath", include the directory part of the
     filename, but not the extension.

     Given the argument "fullpathext", include the directory part of the
     filename and the extension.

 -- : VAL = ignore_function_time_stamp ()
 -- : OLD_VAL = ignore_function_time_stamp (NEW_VAL)
     Query or set the internal variable that controls whether Octave
     checks the time stamp on files each time it looks up functions
     defined in function files.

     If the internal variable is set to "system", Octave will not
     automatically recompile function files in subdirectories of
     ‘OCTAVE-HOME/lib/VERSION’ if they have changed since they were last
     compiled, but will recompile other function files in the search
     path if they change.

     If set to "all", Octave will not recompile any function files
     unless their definitions are removed with ‘clear’.

     If set to "none", Octave will always check time stamps on files to
     determine whether functions defined in function files need to
     recompiled.

* Menu:

* Manipulating the Load Path::
* Subfunctions::
* Private Functions::
* Nested Functions::
* Overloading and Autoloading::
* Function Locking::
* Function Precedence::

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

   (1) The ‘.m’ suffix was chosen for compatibility with MATLAB.


File: octave.info,  Node: Manipulating the Load Path,  Next: Subfunctions,  Up: Function Files

11.9.1 Manipulating the Load Path
---------------------------------

When a function is called, Octave searches a list of directories for a
file that contains the function declaration.  This list of directories
is known as the load path.  By default the load path contains a list of
directories distributed with Octave plus the current working directory.
To see your current load path call the ‘path’ function without any input
or output arguments.

   It is possible to add or remove directories to or from the load path
using ‘addpath’ and ‘rmpath’.  As an example, the following code adds
‘~/Octave’ to the load path.

     addpath ("~/Octave")

After this the directory ‘~/Octave’ will be searched for functions.

 -- : addpath (DIR1, ...)
 -- : addpath (DIR1, ..., OPTION)
     Add named directories to the function search path.

     If OPTION is "-begin" or 0 (the default), prepend the directory
     name to the current path.  If OPTION is "-end" or 1, append the
     directory name to the current path.  Directories added to the path
     must exist.

     In addition to accepting individual directory arguments, lists of
     directory names separated by ‘pathsep’ are also accepted.  For
     example:

          addpath ("dir1:/dir2:~/dir3")

     For each directory that is added, and that was not already in the
     path, ‘addpath’ checks for the existence of a file named ‘PKG_ADD’
     (note lack of .m extension) and runs it if it exists.

     See also: *note path: XREFpath, *note rmpath: XREFrmpath, *note
     genpath: XREFgenpath, *note pathdef: XREFpathdef, *note savepath:
     XREFsavepath, *note pathsep: XREFpathsep.

 -- : genpath (DIR)
 -- : genpath (DIR, SKIP, ...)
     Return a path constructed from DIR and all its subdirectories.

     The path does not include package directories (beginning with ‘+’),
     old-style class directories (beginning with ‘@’), ‘private’
     directories, or any subdirectories of these types.

     If additional string parameters are given, the resulting path will
     exclude directories with those names.

     See also: *note path: XREFpath, *note addpath: XREFaddpath.

 -- : rmpath (DIR1, ...)
     Remove DIR1, ... from the current function search path.

     In addition to accepting individual directory arguments, lists of
     directory names separated by ‘pathsep’ are also accepted.  For
     example:

          rmpath ("dir1:/dir2:~/dir3")

     For each directory that is removed, ‘rmpath’ checks for the
     existence of a file named ‘PKG_DEL’ (note lack of .m extension) and
     runs it if it exists.

     See also: *note path: XREFpath, *note addpath: XREFaddpath, *note
     genpath: XREFgenpath, *note pathdef: XREFpathdef, *note savepath:
     XREFsavepath, *note pathsep: XREFpathsep.

 -- : savepath ()
 -- : savepath (FILE)
 -- : STATUS = savepath (...)
     Save the unique portion of the current function search path that is
     not set during Octave’s initialization process to FILE.

     If FILE is omitted, Octave looks in the current directory for a
     project-specific ‘.octaverc’ file in which to save the path
     information.  If no such file is present then the user’s
     configuration file ‘~/.octaverc’ is used.

     If successful, ‘savepath’ returns 0.

     The ‘savepath’ function makes it simple to customize a user’s
     configuration file to restore the working paths necessary for a
     particular instance of Octave.  Assuming no filename is specified,
     Octave will automatically restore the saved directory paths from
     the appropriate ‘.octaverc’ file when starting up.  If a filename
     has been specified then the paths may be restored manually by
     calling ‘source FILE’.

     See also: *note path: XREFpath, *note addpath: XREFaddpath, *note
     rmpath: XREFrmpath, *note genpath: XREFgenpath, *note pathdef:
     XREFpathdef.

 -- : path ()
 -- : STR = path ()
 -- : STR = path (PATH1, ...)
     Modify or display Octave’s load path.

     If NARGIN and NARGOUT are zero, display the elements of Octave’s
     load path in an easy to read format.

     If NARGIN is zero and nargout is greater than zero, return the
     current load path.

     If NARGIN is greater than zero, concatenate the arguments,
     separating them with ‘pathsep’.  Set the internal search path to
     the result and return it.

     No checks are made for duplicate elements.

     See also: *note addpath: XREFaddpath, *note rmpath: XREFrmpath,
     *note genpath: XREFgenpath, *note pathdef: XREFpathdef, *note
     savepath: XREFsavepath, *note pathsep: XREFpathsep.

 -- : VAL = pathdef ()
     Return the default path for Octave.

     The path information is extracted from one of four sources.  The
     possible sources, in order of preference, are:

       1. ‘.octaverc’

       2. ‘~/.octaverc’

       3. ‘<OCTAVE_HOME>/.../<version>/m/startup/octaverc’

       4. Octave’s path prior to changes by any octaverc file.

     See also: *note path: XREFpath, *note addpath: XREFaddpath, *note
     rmpath: XREFrmpath, *note genpath: XREFgenpath, *note savepath:
     XREFsavepath.

 -- : VAL = pathsep ()
     Query the character used to separate directories in a path.

     See also: *note filesep: XREFfilesep.

 -- : rehash ()
     Reinitialize Octave’s load path directory cache.

 -- : FNAME = file_in_loadpath (FILE)
 -- : FNAME = file_in_loadpath (FILE, "all")
     Return the absolute name of FILE if it can be found in the list of
     directories specified by ‘path’.

     If no file is found, return an empty character string.

     When FILE is already an absolute name, the name is checked against
     the file system instead of Octave’s loadpath.  In this case, if
     FILE exists it will be returned in FNAME, otherwise an empty string
     is returned.

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

     If the second 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_path: XREFfile_in_path, *note
     dir_in_loadpath: XREFdir_in_loadpath, *note path: XREFpath.

 -- : restoredefaultpath ()
     Restore Octave’s path to its initial state at startup.

     See also: *note path: XREFpath, *note addpath: XREFaddpath, *note
     rmpath: XREFrmpath, *note genpath: XREFgenpath, *note pathdef:
     XREFpathdef, *note savepath: XREFsavepath, *note pathsep:
     XREFpathsep.

 -- : command_line_path ()
     Return the command line path variable.

     See also: *note path: XREFpath, *note addpath: XREFaddpath, *note
     rmpath: XREFrmpath, *note genpath: XREFgenpath, *note pathdef:
     XREFpathdef, *note savepath: XREFsavepath, *note pathsep:
     XREFpathsep.

 -- : DIRNAME = dir_in_loadpath (DIR)
 -- : DIRNAME = dir_in_loadpath (DIR, "all")
     Return the absolute name of the loadpath element matching DIR if it
     can be found in the list of directories specified by ‘path’.

     If no match is found, return an empty character string.

     The match is performed at the end of each path element.  For
     example, if DIR is "foo/bar", it matches the path element
     "/some/dir/foo/bar", but not "/some/dir/foo/bar/baz"
     "/some/dir/allfoo/bar".  When DIR is an absolute name, rather than
     just a path fragment, it is matched against the file system instead
     of Octave’s loadpath.  In this case, if DIR exists it will be
     returned in DIRNAME, otherwise an empty string is returned.

     If the optional second argument is supplied, return a cell array
     containing all name matches rather than just the first.

     See also: *note file_in_path: XREFfile_in_path, *note
     file_in_loadpath: XREFfile_in_loadpath, *note path: XREFpath.


File: octave.info,  Node: Subfunctions,  Next: Private Functions,  Prev: Manipulating the Load Path,  Up: Function Files

11.9.2 Subfunctions
-------------------

A function file may contain secondary functions called “subfunctions”.
These secondary functions are only visible to the other functions in the
same function file.  For example, a file ‘f.m’ containing

     function f ()
       printf ("in f, calling g\n");
       g ()
     endfunction
     function g ()
       printf ("in g, calling h\n");
       h ()
     endfunction
     function h ()
       printf ("in h\n")
     endfunction

defines a main function ‘f’ and two subfunctions.  The subfunctions ‘g’
and ‘h’ may only be called from the main function ‘f’ or from the other
subfunctions, but not from outside the file ‘f.m’.

 -- : localfunctions ()
     Return a list of all local functions, i.e., subfunctions, within
     the current file.

     The return value is a column cell array of function handles to all
     local functions accessible from the function from which
     ‘localfunctions’ is called.  Nested functions are _not_ included in
     the list.

     If the call is from the command line, an anonymous function, or a
     script, the return value is an empty cell array.

     See also: *note functions: XREFfunctions.


File: octave.info,  Node: Private Functions,  Next: Nested Functions,  Prev: Subfunctions,  Up: Function Files

11.9.3 Private Functions
------------------------

In many cases one function needs to access one or more helper functions.
If the helper function is limited to the scope of a single function,
then subfunctions as discussed above might be used.  However, if a
single helper function is used by more than one function, then this is
no longer possible.  In this case the helper functions might be placed
in a subdirectory, called "private", of the directory in which the
functions needing access to this helper function are found.

   As a simple example, consider a function ‘func1’, that calls a helper
function ‘func2’ to do much of the work.  For example:

     function y = func1 (x)
       y = func2 (x);
     endfunction

Then if the path to ‘func1’ is ‘<directory>/func1.m’, and if ‘func2’ is
found in the directory ‘<directory>/private/func2.m’, then ‘func2’ is
only available for use of the functions, like ‘func1’, that are found in
‘<directory>’.


File: octave.info,  Node: Nested Functions,  Next: Overloading and Autoloading,  Prev: Private Functions,  Up: Function Files

11.9.4 Nested Functions
-----------------------

Nested functions are similar to subfunctions in that only the main
function is visible outside the file.  However, they also allow for
child functions to access the local variables in their parent function.
This shared access mimics using a global variable to share information —
but a global variable which is not visible to the rest of Octave.  As a
programming strategy, sharing data this way can create code which is
difficult to maintain.  It is recommended to use subfunctions in place
of nested functions when possible.

   As a simple example, consider a parent function ‘foo’, that calls a
nested child function ‘bar’, with a shared variable X.

     function y = foo ()
       x = 10;
       bar ();
       y = x;

       function bar ()
         x = 20;
       endfunction
     endfunction

     foo ()
      ⇒ 20

Notice that there is no special syntax for sharing X.  This can lead to
problems with accidental variable sharing between a parent function and
its child.  While normally variables are inherited, child function
parameters and return values are local to the child function.

   Now consider the function ‘foobar’ that uses variables X and Y.
‘foobar’ calls a nested function ‘foo’ which takes X as a parameter and
returns Y.  ‘foo’ then calls ‘bat’ which does some computation.

     function z = foobar ()
       x = 0;
       y = 0;
       z = foo (5);
       z += x + y;

       function y = foo (x)
         y = x + bat ();

         function z = bat ()
           z = x;
         endfunction
       endfunction
     endfunction

     foobar ()
         ⇒ 10

It is important to note that the X and Y in ‘foobar’ remain zero, as in
‘foo’ they are a return value and parameter respectively.  The X in
‘bat’ refers to the X in ‘foo’.

   Variable inheritance leads to a problem for ‘eval’ and scripts.  If a
new variable is created in a parent function, it is not clear what
should happen in nested child functions.  For example, consider a parent
function ‘foo’ with a nested child function ‘bar’:

     function y = foo (to_eval)
       bar ();
       eval (to_eval);

       function bar ()
         eval ("x = 100;");
         eval ("y = x;");
       endfunction
     endfunction

     foo ("x = 5;")
         ⇒ error: can not add variable "x" to a static workspace

     foo ("y = 10;")
         ⇒ 10

     foo ("")
         ⇒ 100

The parent function ‘foo’ is unable to create a new variable X, but the
child function ‘bar’ was successful.  Furthermore, even in an ‘eval’
statement Y in ‘bar’ is the same Y as in its parent function ‘foo’.  The
use of ‘eval’ in conjunction with nested functions is best avoided.

   As with subfunctions, only the first nested function in a file may be
called from the outside.  Inside a function the rules are more
complicated.  In general a nested function may call:

  0. Globally visible functions

  1. Any function that the nested function’s parent can call

  2. Sibling functions (functions that have the same parents)

  3. Direct children

   As a complex example consider a parent function ‘ex_top’ with two
child functions, ‘ex_a’ and ‘ex_b’.  In addition, ‘ex_a’ has two more
child functions, ‘ex_aa’ and ‘ex_ab’.  For example:

     function ex_top ()
       ## Can call: ex_top, ex_a, and ex_b
       ## Can NOT call: ex_aa and ex_ab

       function ex_a ()
         ## Can call everything

         function ex_aa ()
           ## Can call everything
         endfunction

         function ex_ab ()
           ## Can call everything
         endfunction
       endfunction

       function ex_b ()
         ## Can call: ex_top, ex_a, and ex_b
         ## Can NOT call: ex_aa and ex_ab
       endfunction
     endfunction


File: octave.info,  Node: Overloading and Autoloading,  Next: Function Locking,  Prev: Nested Functions,  Up: Function Files

11.9.5 Overloading and Autoloading
----------------------------------

Functions can be overloaded to work with different input arguments.  For
example, the operator ’+’ has been overloaded in Octave to work with
single, double, uint8, int32, and many other arguments.  The preferred
way to overload functions is through classes and object oriented
programming (*note Function Overloading::).  Occasionally, however, one
needs to undo user overloading and call the default function associated
with a specific type.  The ‘builtin’ function exists for this purpose.

 -- : [...] = builtin (F, ...)
     Call the base function F even if F is overloaded to another
     function for the given type signature.

     This is normally useful when doing object-oriented programming and
     there is a requirement to call one of Octave’s base functions
     rather than the overloaded one of a new class.

     A trivial example which redefines the ‘sin’ function to be the
     ‘cos’ function shows how ‘builtin’ works.

          sin (0)
            ⇒ 0
          function y = sin (x), y = cos (x); endfunction
          sin (0)
            ⇒ 1
          builtin ("sin", 0)
            ⇒ 0

   A single dynamically linked file might define several functions.
However, as Octave searches for functions based on the functions
filename, Octave needs a manner in which to find each of the functions
in the dynamically linked file.  On operating systems that support
symbolic links, it is possible to create a symbolic link to the original
file for each of the functions which it contains.

   However, there is at least one well known operating system that
doesn’t support symbolic links.  Making copies of the original file for
each of the functions is undesirable as it increases the amount of disk
space used by Octave.  Instead Octave supplies the ‘autoload’ function,
that permits the user to define in which file a certain function will be
found.

 -- : AUTOLOAD_MAP = autoload ()
 -- : autoload (FUNCTION, FILE)
 -- : autoload (..., "remove")
     Define FUNCTION to autoload from FILE.

     The second argument, FILE, should be an absolute filename or a file
     name in the same directory as the function or script from which the
     autoload command was run.  FILE _should not_ depend on the Octave
     load path.

     Normally, calls to ‘autoload’ appear in PKG_ADD script files that
     are evaluated when a directory is added to Octave’s load path.  To
     avoid having to hardcode directory names in FILE, if FILE is in the
     same directory as the PKG_ADD script then

          autoload ("foo", "bar.oct");

     will load the function ‘foo’ from the file ‘bar.oct’.  The above
     usage when ‘bar.oct’ is not in the same directory, or usages such
     as

          autoload ("foo", file_in_loadpath ("bar.oct"))

     are strongly discouraged, as their behavior may be unpredictable.

     With no arguments, return a structure containing the current
     autoload map.

     If a third argument "remove" is given, the function is cleared and
     not loaded anymore during the current Octave session.

     See also: *note PKG_ADD: XREFPKG_ADD.


File: octave.info,  Node: Function Locking,  Next: Function Precedence,  Prev: Overloading and Autoloading,  Up: Function Files

11.9.6 Function Locking
-----------------------

It is sometime desirable to lock a function into memory with the ‘mlock’
function.  This is typically used for dynamically linked functions in
Oct-files or mex-files that contain some initialization, and it is
desirable that calling ‘clear’ does not remove this initialization.

   As an example,

     function my_function ()
       mlock ();
       ...

prevents ‘my_function’ from being removed from memory after it is
called, even if ‘clear’ is called.  It is possible to determine if a
function is locked into memory with the ‘mislocked’, and to unlock a
function with ‘munlock’, which the following illustrates.

     my_function ();
     mislocked ("my_function")
     ⇒ ans = 1
     munlock ("my_function");
     mislocked ("my_function")
     ⇒ ans = 0

   A common use of ‘mlock’ is to prevent persistent variables from being
removed from memory, as the following example shows:

     function count_calls ()
       mlock ();
       persistent calls = 0;
       printf ("'count_calls' has been called %d times\n",
               ++calls);
     endfunction

     count_calls ();
     ⊣ 'count_calls' has been called 1 times

     clear count_calls
     count_calls ();
     ⊣ 'count_calls' has been called 2 times

   ‘mlock’ might equally be used to prevent changes to a function from
having effect in Octave, though a similar effect can be had with the
‘ignore_function_time_stamp’ function.

 -- : mlock ()
     Lock the current function into memory so that it can’t be cleared.

     See also: *note munlock: XREFmunlock, *note mislocked:
     XREFmislocked, *note persistent: XREFpersistent.

 -- : munlock ()
 -- : munlock (FCN)
     Unlock the named function FCN.

     If no function is named then unlock the current function.

     See also: *note mlock: XREFmlock, *note mislocked: XREFmislocked,
     *note persistent: XREFpersistent.

 -- : mislocked ()
 -- : mislocked (FCN)
     Return true if the named function FCN is locked.

     If no function is named then return true if the current function is
     locked.

     See also: *note mlock: XREFmlock, *note munlock: XREFmunlock, *note
     persistent: XREFpersistent.


File: octave.info,  Node: Function Precedence,  Prev: Function Locking,  Up: Function Files

11.9.7 Function Precedence
--------------------------

Given the numerous different ways that Octave can define a function, it
is possible and even likely that multiple versions of a function, might
be defined within a particular scope.  The precedence of which function
will be used within a particular scope is given by

  1. Subfunction A subfunction with the required function name in the
     given scope.

  2. Private function A function defined within a private directory of
     the directory which contains the current function.

  3. Class constructor A function that constructs a user class as
     defined in chapter *note Object Oriented Programming::.

  4. Class method An overloaded function of a class as in chapter *note
     Object Oriented Programming::.

  5. Command-line Function A function that has been defined on the
     command-line.

  6. Autoload function A function that is marked as autoloaded with
     *Note autoload: XREFautoload.

  7. A Function on the Path A function that can be found on the users
     load-path.  There can also be Oct-file, mex-file or m-file versions
     of this function and the precedence between these versions are in
     that order.

  8. Built-in function A function that is a part of core Octave such as
     ‘numel’, ‘size’, etc.


File: octave.info,  Node: Script Files,  Next: Function Handles Anonymous Functions Inline Functions,  Prev: Function Files,  Up: Functions and Scripts

11.10 Script Files
==================

A script file is a file containing (almost) any sequence of Octave
commands.  It is read and evaluated just as if you had typed each
command at the Octave prompt, and provides a convenient way to perform a
sequence of commands that do not logically belong inside a function.

   Unlike a function file, a script file must _not_ begin with the
keyword ‘function’.  If it does, Octave will assume that it is a
function file, and that it defines a single function that should be
evaluated as soon as it is defined.

   A script file also differs from a function file in that the variables
named in a script file are not local variables, but are in the same
scope as the other variables that are visible on the command line.

   Even though a script file may not begin with the ‘function’ keyword,
it is possible to define more than one function in a single script file
and load (but not execute) all of them at once.  To do this, the first
token in the file (ignoring comments and other white space) must be
something other than ‘function’.  If you have no other statements to
evaluate, you can use a statement that has no effect, like this:

     # Prevent Octave from thinking that this
     # is a function file:

     1;

     # Define function one:

     function one ()
       ...

   To have Octave read and compile these functions into an internal
form, you need to make sure that the file is in Octave’s load path
(accessible through the ‘path’ function), then simply type the base name
of the file that contains the commands.  (Octave uses the same rules to
search for script files as it does to search for function files.)

   If the first token in a file (ignoring comments) is ‘function’,
Octave will compile the function and try to execute it, printing a
message warning about any non-whitespace characters that appear after
the function definition.

   Note that Octave does not try to look up the definition of any
identifier until it needs to evaluate it.  This means that Octave will
compile the following statements if they appear in a script file, or are
typed at the command line,

     # not a function file:
     1;
     function foo ()
       do_something ();
     endfunction
     function do_something ()
       do_something_else ();
     endfunction

even though the function ‘do_something’ is not defined before it is
referenced in the function ‘foo’.  This is not an error because Octave
does not need to resolve all symbols that are referenced by a function
until the function is actually evaluated.

   Since Octave doesn’t look for definitions until they are needed, the
following code will always print ‘bar = 3’ whether it is typed directly
on the command line, read from a script file, or is part of a function
body, even if there is a function or script file called ‘bar.m’ in
Octave’s path.

     eval ("bar = 3");
     bar

   Code like this appearing within a function body could fool Octave if
definitions were resolved as the function was being compiled.  It would
be virtually impossible to make Octave clever enough to evaluate this
code in a consistent fashion.  The parser would have to be able to
perform the call to ‘eval’ at compile time, and that would be impossible
unless all the references in the string to be evaluated could also be
resolved, and requiring that would be too restrictive (the string might
come from user input, or depend on things that are not known until the
function is evaluated).

   Although Octave normally executes commands from script files that
have the name ‘FILE.m’, you can use the function ‘source’ to execute
commands from any file.

 -- : source (FILE)
 -- : source (FILE, CONTEXT)
     Parse and execute the contents of FILE.

     Without specifying CONTEXT, this is equivalent to executing
     commands from a script file, but without requiring the file to be
     named ‘FILE.m’ or to be on the execution path.

     Instead of the current context, the script may be executed in
     either the context of the function that called the present function
     ("caller"), or the top-level context ("base").

     See also: *note run: XREFrun.

* Menu:

* Publish Octave Script Files::
* Publishing Markup::


File: octave.info,  Node: Publish Octave Script Files,  Next: Publishing Markup,  Up: Script Files

11.10.1 Publish Octave Script Files
-----------------------------------

The function ‘publish’ provides a dynamic possibility to document your
script file.  Unlike static documentation, ‘publish’ runs the script
file, saves any figures and output while running the script, and
presents them alongside static documentation in a desired output format.
The static documentation can make use of *note Publishing Markup:: to
enhance and customize the output.

 -- : publish (FILE)
 -- : publish (FILE, OUTPUT_FORMAT)
 -- : publish (FILE, OPTION1, VALUE1, ...)
 -- : publish (FILE, OPTIONS)
 -- : OUTPUT_FILE = publish (FILE, ...)

     Generate a report from the Octave script file FILE in one of
     several output formats.

     The generated reports interpret any Publishing Markup in comments,
     which is explained in detail in the GNU Octave manual.  Assume the
     following example, using some Publishing Markup, to be the contents
     of the script file ‘pub_example.m’:

          ## Headline title
          #
          # Some *bold*, _italic_, or |monospaced| Text with
          # a <https://www.octave.org link to *GNU Octave*>.
          ##

          # "Real" Octave commands to be evaluated
          sombrero ()

          %% MATLAB comment style ('%') is supported as well
          %
          % * Bulleted list item 1
          % * Bulleted list item 2
          %
          % # Numbered list item 1
          % # Numbered list item 2

     To publish this script file, type ‘publish ("pub_example.m")’.

     With only FILE given, a HTML report is generated in a subdirectory
     ‘html’ relative to the current working directory.  The Octave
     commands are evaluated in a separate context and any figures
     created while executing the script file are included in the report.
     All formatting syntax of FILE is treated according to the specified
     output format and included in the report.

     Using ‘publish (FILE, OUTPUT_FORMAT)’ is equivalent to the function
     call using a structure

          OPTIONS.format = OUTPUT_FORMAT;
          publish (FILE, OPTIONS)

     which is described below.  The same holds for using option/value
     pairs

          OPTIONS.OPTION1 = VALUE1;
          publish (FILE, OPTIONS)

     The structure OPTIONS can have the following field names.  If a
     field name is not specified, the default value is used:

        • ‘format’ — Output format of the published script file, one of

          ‘html’ (default), ‘doc’, ‘latex’, ‘ppt’, ‘pdf’, or ‘xml’.

          The output formats ‘doc’, ‘ppt’, and ‘xml’ are not currently
          supported.  To generate a ‘doc’ report, open a generated
          ‘html’ report with your office suite.

          In Octave custom formats are supported by implementing all
          callback subfunctions in a function file named
          ‘__publish_<custom format>_output__.m’.  To obtain a template
          for the HTML format type:

               edit (fullfile (fileparts (which ("publish")), ...
                     "private", "__publish_html_output__.m"))

        • ‘outputDir’ — Full path of the directory where the generated
          report will be located.  If no directory is given, the report
          is generated in a subdirectory ‘html’ relative to the current
          working directory.

        • ‘stylesheet’ — Not supported, only for MATLAB compatibility.

        • ‘createThumbnail’ — Not supported, only for MATLAB
          compatibility.

        • ‘figureSnapMethod’ — Not supported, only for MATLAB
          compatibility.

        • ‘imageFormat’ — Desired format for any images produced while
          evaluating the code.  The allowed image formats depend on the
          output format:

             • ‘html’, ‘xml’ — ‘png’ (default), any image format
               supported by Octave

             • ‘latex’ — ‘epsc2’ (default), any image format supported
               by Octave

             • ‘pdf’ — ‘jpg’ (default) or ‘bmp’, note MATLAB uses ‘bmp’
               as default

             • ‘doc’ or ‘ppt’ — ‘png’ (default), ‘jpg’, ‘bmp’, or ‘tiff’

        • ‘maxWidth’ and ‘maxHeight’ — Maximum width (height) of the
          produced images in pixels.  An empty value means no
          restriction.  Both values must be set in order for the option
          to work properly.

          ‘[]’ (default), integer value ≥ 0

        • ‘useNewFigure’ — Use a new figure window for figures created
          by the evaluated code.  This avoids side effects with already
          opened figure windows.

          ‘true’ (default) or ‘false’

        • ‘evalCode’ — Evaluate code of the Octave source file

          ‘true’ (default) or ‘false’

        • ‘catchError’ — Catch errors while evaluating code and continue

          ‘true’ (default) or ‘false’

        • ‘codeToEvaluate’ — Octave commands that should be evaluated
          prior to publishing the script file.  These Octave commands do
          not appear in the generated report.

        • ‘maxOutputLines’ — Maximum number of output lines from code
          evaluation which are included in output.

          ‘Inf’ (default) or integer value > 0

        • ‘showCode’ — Show the evaluated Octave commands in the
          generated report

          ‘true’ (default) or ‘false’

     The option output OUTPUT_FILE is a string with path and file name
     of the generated report.

     See also: *note grabcode: XREFgrabcode.

   The counterpart to ‘publish’ is ‘grabcode’:

 -- : grabcode (URL)
 -- : grabcode (FILENAME)
 -- : CODE_STR = grabcode (...)

     Grab the code from a report created by the ‘publish’ function.

     The grabbed code inside the published report must be enclosed by
     the strings ‘##### SOURCE BEGIN #####’ and ‘##### SOURCE END
     #####’.  The ‘publish’ function creates this format automatically.

     If no return value is requested the code is saved to a temporary
     file and opened in the default editor.  NOTE: The temporary file
     must be saved under a new or the code will be lost.

     If an output is requested the grabbed code will be returned as
     string CODE_STR.

     Example:

          publish ("my_script.m");
          grabcode ("html/my_script.html");

     The example above publishes ‘my_script.m’ to the default location
     ‘html/my_script.html’.  Next, the published Octave script is
     grabbed to edit its content in a new temporary file.

     See also: *note publish: XREFpublish.


File: octave.info,  Node: Publishing Markup,  Prev: Publish Octave Script Files,  Up: Script Files

11.10.2 Publishing Markup
-------------------------

* Menu:

* Using Publishing Markup in Script Files::
* Text Formatting::
* Sections::
* Preformatted Code::
* Preformatted Text::
* Bulleted Lists::
* Numbered Lists::
* Including File Content::
* Including Graphics::
* Including URLs::
* Mathematical Equations::
* HTML Markup::
* LaTeX Markup::


File: octave.info,  Node: Using Publishing Markup in Script Files,  Next: Text Formatting,  Up: Publishing Markup

11.10.2.1 Using Publishing Markup in Script Files
.................................................

To use Publishing Markup, start by typing ‘##’ or ‘%%’ at the beginning
of a new line.  For MATLAB compatibility ‘%%%’ is treated the same way
as ‘%%’.

   The lines following ‘##’ or ‘%%’ start with one of either ‘#’ or ‘%’
followed by at least one space.  These lines are interpreted as section.
A section ends at the first line not starting with ‘#’ or ‘%’, or when
the end of the document is reached.

   A section starting in the first line of the document, followed by
another start of a section that might be empty, is interpreted as a
document title and introduction text.

   See the example below for clarity:

     %% Headline title
     %
     % Some *bold*, _italic_, or |monospaced| Text with
     % a <https://www.octave.org link to GNU Octave>.
     %%

     # "Real" Octave commands to be evaluated
     sombrero ()

     ## Octave comment style supported as well
     #
     # * Bulleted list item 1
     # * Bulleted list item 2
     #
     # # Numbered list item 1
     # # Numbered list item 2


File: octave.info,  Node: Text Formatting,  Next: Sections,  Prev: Using Publishing Markup in Script Files,  Up: Publishing Markup

11.10.2.2 Text Formatting
.........................

Basic text formatting is supported inside sections, see the example
given below:

     ##
     # *bold*, _italic_, or |monospaced| Text

   Additionally two trademark symbols are supported, just embrace the
letters ‘TM’ or ‘R’.

     ##
     # (TM) or (R)


File: octave.info,  Node: Sections,  Next: Preformatted Code,  Prev: Text Formatting,  Up: Publishing Markup

11.10.2.3 Sections
..................

A section is started by typing ‘##’ or ‘%%’ at the beginning of a new
line.  A section title can be provided by writing it, separated by a
space, in the first line after ‘##’ or ‘%%’.  Without a section title,
the section is interpreted as a continuation of the previous section.
For MATLAB compatibility ‘%%%’ is treated the same way as ‘%%’.

     some_code ();

     ## Section 1
     #
     ## Section 2

     some_code ();

     ##
     # Still in section 2

     some_code ();

     %%% Section 3
     %
     %


File: octave.info,  Node: Preformatted Code,  Next: Preformatted Text,  Prev: Sections,  Up: Publishing Markup

11.10.2.4 Preformatted Code
...........................

To write preformatted code inside a section, indent the code by three
spaces after ‘#’ at the beginning of each line and leave the lines above
and below the code blank, except for ‘#’ at the beginning of those
lines.

     ##
     # This is a syntax highlighted for-loop:
     #
     #   for i = 1:5
     #     disp (i);
     #   endfor
     #
     # And more usual text.


File: octave.info,  Node: Preformatted Text,  Next: Bulleted Lists,  Prev: Preformatted Code,  Up: Publishing Markup

11.10.2.5 Preformatted Text
...........................

To write preformatted text inside a section, indent the code by two
spaces after ‘#’ at the beginning of each line and leave the lines above
and below the preformatted text blank, except for ‘#’ at the beginning
of those lines.

     ##
     # This following text is preformatted:
     #
     #  "To be, or not to be: that is the question:
     #  Whether 'tis nobler in the mind to suffer
     #  The slings and arrows of outrageous fortune,
     #  Or to take arms against a sea of troubles,
     #  And by opposing end them?  To die: to sleep;"
     #
     #  --"Hamlet" by W. Shakespeare


File: octave.info,  Node: Bulleted Lists,  Next: Numbered Lists,  Prev: Preformatted Text,  Up: Publishing Markup

11.10.2.6 Bulleted Lists
........................

To create a bulleted list, type

     ##
     #
     # * Bulleted list item 1
     # * Bulleted list item 2
     #

to get output like

   • Bulleted list item 1

   • Bulleted list item 2

   Notice the blank lines, except for the ‘#’ or ‘%’ before and after
the bulleted list!


File: octave.info,  Node: Numbered Lists,  Next: Including File Content,  Prev: Bulleted Lists,  Up: Publishing Markup

11.10.2.7 Numbered Lists
........................

To create a numbered list, type

     ##
     #
     # # Numbered list item 1
     # # Numbered list item 2
     #

to get output like

  1. Numbered list item 1

  2. Numbered list item 2

   Notice the blank lines, except for the ‘#’ or ‘%’ before and after
the numbered list!


File: octave.info,  Node: Including File Content,  Next: Including Graphics,  Prev: Numbered Lists,  Up: Publishing Markup

11.10.2.8 Including File Content
................................

To include the content of an external file, e.g., a file called
‘my_function.m’ at the same location as the published Octave script, use
the following syntax to include it with Octave syntax highlighting.

   Alternatively, you can write the full or relative path to the file.

     ##
     #
     # <include>my_function.m</include>
     #
     # <include>/full/path/to/my_function.m</include>
     #
     # <include>../relative/path/to/my_function.m</include>
     #


File: octave.info,  Node: Including Graphics,  Next: Including URLs,  Prev: Including File Content,  Up: Publishing Markup

11.10.2.9 Including Graphics
............................

To include external graphics, e.g., a graphic called ‘my_graphic.png’ at
the same location as the published Octave script, use the following
syntax.

   Alternatively, you can write the full path to the graphic.

     ##
     #
     # <<my_graphic.png>>
     #
     # <</full/path/to/my_graphic.png>>
     #
     # <<../relative/path/to/my_graphic.png>>
     #


File: octave.info,  Node: Including URLs,  Next: Mathematical Equations,  Prev: Including Graphics,  Up: Publishing Markup

11.10.2.10 Including URLs
.........................

Basically, a URL is written between an opening ‘<’ and a closing ‘>’
angle.

     ##
     # <https://www.octave.org>

   Text that is within these angles and separated by at least one space
from the URL is a displayed text for the link.

     ##
     # <https://www.octave.org GNU Octave>

   A link starting with ‘<octave:’ followed by the name of a GNU Octave
function, optionally with a displayed text, results in a link to the
online GNU Octave documentations function index.

     ##
     # <octave:DISP The display function>


File: octave.info,  Node: Mathematical Equations,  Next: HTML Markup,  Prev: Including URLs,  Up: Publishing Markup

11.10.2.11 Mathematical Equations
.................................

One can insert LaTeX inline math, surrounded by single ‘$’ signs, or
displayed math, surrounded by double ‘$$’ signs, directly inside
sections.

     ##
     # Some shorter inline equation $e^{ix} = \cos x + i\sin x$.
     #
     # Or more complicated formulas as displayed math:
     # $$e^x = \lim_{n\rightarrow\infty}\left(1+\dfrac{x}{n}\right)^{n}.$$


File: octave.info,  Node: HTML Markup,  Next: LaTeX Markup,  Prev: Mathematical Equations,  Up: Publishing Markup

11.10.2.12 HTML Markup
......................

If the published output is a HTML report, you can insert HTML markup,
that is only visible in this kind of output.

     ##
     # <html>
     # <table style="border:1px solid black;">
     # <tr><td>1</td><td>2</td></tr>
     # <tr><td>3</td><td>3</td></tr>
     # </html>


File: octave.info,  Node: LaTeX Markup,  Prev: HTML Markup,  Up: Publishing Markup

11.10.2.13 LaTeX Markup
.......................

If the published output is a LaTeX or PDF report, you can insert LaTeX
markup, that is only visible in this kind of output.

     ##
     # <latex>
     # Some output only visible in LaTeX or PDF reports.
     # \begin{equation}
     # e^x = \lim\limits_{n\rightarrow\infty}\left(1+\dfrac{x}{n}\right)^{n}
     # \end{equation}
     # </latex>


File: octave.info,  Node: Function Handles Anonymous Functions Inline Functions,  Next: Commands,  Prev: Script Files,  Up: Functions and Scripts

11.11 Function Handles, Anonymous Functions, Inline Functions
=============================================================

It can be very convenient store a function in a variable so that it can
be passed to a different function.  For example, a function that
performs numerical minimization needs access to the function that should
be minimized.

* Menu:

* Function Handles::
* Anonymous Functions::
* Inline Functions::


File: octave.info,  Node: Function Handles,  Next: Anonymous Functions,  Up: Function Handles Anonymous Functions Inline Functions

11.11.1 Function Handles
------------------------

A function handle is a pointer to another function and is defined with
the syntax

     @FUNCTION-NAME

For example,

     f = @sin;

creates a function handle called ‘f’ that refers to the function ‘sin’.

   Function handles are used to call other functions indirectly, or to
pass a function as an argument to another function like ‘quad’ or
‘fsolve’.  For example:

     f = @sin;
     quad (f, 0, pi)
         ⇒ 2

   You may use ‘feval’ to call a function using function handle, or
simply write the name of the function handle followed by an argument
list.  If there are no arguments, you must use an empty argument list
‘()’.  For example:

     f = @sin;
     feval (f, pi/4)
         ⇒ 0.70711
     f (pi/4)
         ⇒ 0.70711

 -- : is_function_handle (X)
     Return true if X is a function handle.

     See also: *note isa: XREFisa, *note typeinfo: XREFtypeinfo, *note
     class: XREFclass, *note functions: XREFfunctions.

 -- : S = functions (FCN_HANDLE)
     Return a structure containing information about the function handle
     FCN_HANDLE.

     The structure S always contains these three fields:

     function
          The function name.  For an anonymous function (no name) this
          will be the actual function definition.

     type
          Type of the function.

          anonymous
               The function is anonymous.

          private
               The function is private.

          overloaded
               The function overloads an existing function.

          simple
               The function is a built-in or m-file function.

          subfunction
               The function is a subfunction within an m-file.

     file
          The m-file that will be called to perform the function.  This
          field is empty for anonymous and built-in functions.

     In addition, some function types may return more information in
     additional fields.

     *Warning:* ‘functions’ is provided for debugging purposes only.
     Its behavior may change in the future and programs should not
     depend on any particular output format.

     See also: *note func2str: XREFfunc2str, *note str2func:
     XREFstr2func.

 -- : func2str (FCN_HANDLE)
     Return a string containing the name of the function referenced by
     the function handle FCN_HANDLE.

     See also: *note str2func: XREFstr2func, *note functions:
     XREFfunctions.

 -- : str2func (FCN_NAME)
 -- : str2func (FCN_NAME, "global")
     Return a function handle constructed from the string FCN_NAME.

     If the optional "global" argument is passed, locally visible
     functions are ignored in the lookup.

     See also: *note func2str: XREFfunc2str, *note inline: XREFinline,
     *note functions: XREFfunctions.


File: octave.info,  Node: Anonymous Functions,  Next: Inline Functions,  Prev: Function Handles,  Up: Function Handles Anonymous Functions Inline Functions

11.11.2 Anonymous Functions
---------------------------

Anonymous functions are defined using the syntax

     @(ARGUMENT-LIST) EXPRESSION

Any variables that are not found in the argument list are inherited from
the enclosing scope.  Anonymous functions are useful for creating simple
unnamed functions from expressions or for wrapping calls to other
functions to adapt them for use by functions like ‘quad’.  For example,

     f = @(x) x.^2;
     quad (f, 0, 10)
         ⇒ 333.33

creates a simple unnamed function from the expression ‘x.^2’ and passes
it to ‘quad’,

     quad (@(x) sin (x), 0, pi)
         ⇒ 2

wraps another function, and

     a = 1;
     b = 2;
     quad (@(x) betainc (x, a, b), 0, 0.4)
         ⇒ 0.13867

adapts a function with several parameters to the form required by
‘quad’.  In this example, the values of A and B that are passed to
‘betainc’ are inherited from the current environment.

   Note that for performance reasons it is better to use handles to
existing Octave functions, rather than to define anonymous functions
which wrap an existing function.  The integration of ‘sin (x)’ is 5X
faster if the code is written as

     quad (@sin, 0, pi)

rather than using the anonymous function ‘@(x) sin (x)’.  There are many
operators which have functional equivalents that may be better choices
than an anonymous function.  Instead of writing

     f = @(x, y) x + y

this should be coded as

     f = @plus

   *Note Operator Overloading::, for a list of operators which also have
a functional form.


File: octave.info,  Node: Inline Functions,  Prev: Anonymous Functions,  Up: Function Handles Anonymous Functions Inline Functions

11.11.3 Inline Functions
------------------------

An inline function is created from a string containing the function body
using the ‘inline’ function.  The following code defines the function
f(x) = x^2 + 2.

     f = inline ("x^2 + 2");

After this it is possible to evaluate f at any x by writing ‘f(x)’.

   *Caution*: MATLAB has begun the process of deprecating inline
functions.  At some point in the future support will be dropped and
eventually Octave will follow MATLAB and also remove inline functions.
Use anonymous functions in all new code.

 -- : inline (STR)
 -- : inline (STR, ARG1, ...)
 -- : inline (STR, N)
     Create an inline function from the character string STR.

     If called with a single argument, the arguments of the generated
     function are extracted from the function itself.  The generated
     function arguments will then be in alphabetical order.  It should
     be noted that i and j are ignored as arguments due to the ambiguity
     between their use as a variable or their use as an built-in
     constant.  All arguments followed by a parenthesis are considered
     to be functions.  If no arguments are found, a function taking a
     single argument named ‘x’ will be created.

     If the second and subsequent arguments are character strings, they
     are the names of the arguments of the function.

     If the second argument is an integer N, the arguments are "x",
     "P1", ..., "PN".

     Programming Note: The use of ‘inline’ is discouraged and it may be
     removed from a future version of Octave.  The preferred way to
     create functions from strings is through the use of anonymous
     functions (*note Anonymous Functions::) or ‘str2func’.

     See also: *note argnames: XREFargnames, *note formula: XREFformula,
     *note vectorize: XREFvectorize, *note str2func: XREFstr2func.

 -- : argnames (FUN)
     Return a cell array of character strings containing the names of
     the arguments of the inline function FUN.

     See also: *note inline: XREFinline, *note formula: XREFformula,
     *note vectorize: XREFvectorize.

 -- : formula (FUN)
     Return a character string representing the inline function FUN.

     Note that ‘char (FUN)’ is equivalent to ‘formula (FUN)’.

     See also: *note char: XREFchar, *note argnames: XREFargnames, *note
     inline: XREFinline, *note vectorize: XREFvectorize.

 -- : VARS = symvar (STR)
     Identify the symbolic variable names in the string STR.

     Common constant names such as ‘i’, ‘j’, ‘pi’, ‘Inf’ and Octave
     functions such as ‘sin’ or ‘plot’ are ignored.

     Any names identified are returned in a cell array of strings.  The
     array is empty if no variables were found.

     Example:

          symvar ("x^2 + y^2 == 4")
          ⇒ {
               [1,1] = x
               [2,1] = y
             }


File: octave.info,  Node: Commands,  Next: Organization of Functions,  Prev: Function Handles Anonymous Functions Inline Functions,  Up: Functions and Scripts

11.12 Commands
==============

Commands are a special class of functions that only accept string input
arguments.  A command can be called as an ordinary function, but it can
also be called without the parentheses.  For example,

     my_command hello world

is equivalent to

     my_command ("hello", "world")

The general form of a command call is

     CMDNAME ARG1 ARG2 ...

which translates directly to

     CMDNAME ("ARG1", "ARG2", ...)

   Any regular function can be used as a command if it accepts string
input arguments.  For example:

     toupper lower_case_arg
        ⇒ ans = LOWER_CASE_ARG

   One difficulty of commands occurs when one of the string input
arguments is stored in a variable.  Because Octave can’t tell the
difference between a variable name and an ordinary string, it is not
possible to pass a variable as input to a command.  In such a situation
a command must be called as a function.  For example:

     strvar = "hello world";
     toupper strvar
        ⇒ ans = STRVAR
     toupper (strvar)
        ⇒ ans = HELLO WORLD


File: octave.info,  Node: Organization of Functions,  Prev: Commands,  Up: Functions and Scripts

11.13 Organization of Functions Distributed with Octave
=======================================================

Many of Octave’s standard functions are distributed as function files.
They are loosely organized by topic, in subdirectories of
‘OCTAVE-HOME/lib/octave/VERSION/m’, to make it easier to find them.

   The following is a list of all the function file subdirectories, and
the types of functions you will find there.

‘@ftp’
     Class functions for the FTP object.

‘+containers’
     Package for the containers classes.

‘audio’
     Functions for playing and recording sounds.

‘deprecated’
     Out-of-date functions which will eventually be removed from Octave.

‘elfun’
     Elementary functions, principally trigonometric.

‘general’
     Miscellaneous matrix manipulations, like ‘flipud’, ‘rot90’, and
     ‘triu’, as well as other basic functions, like ‘ismatrix’,
     ‘narginchk’, etc.

‘geometry’
     Functions related to Delaunay triangulation.

‘gui’
     Functions for GUI elements like dialog, message box, etc.

‘help’
     Functions for Octave’s built-in help system.

‘image’
     Image processing tools.  These functions require the X Window
     System.

‘io’
     Input-output functions.

‘java’
     Functions related to the Java integration.

‘linear-algebra’
     Functions for linear algebra.

‘miscellaneous’
     Functions that don’t really belong anywhere else.

‘ode’
     Functions to solve ordinary differential equations (ODEs).

‘optimization’
     Functions related to minimization, optimization, and root finding.

‘path’
     Functions to manage the directory path Octave uses to find
     functions.

‘pkg’
     Package manager for installing external packages of functions in
     Octave.

‘plot’
     Functions for displaying and printing two- and three-dimensional
     graphs.

‘polynomial’
     Functions for manipulating polynomials.

‘prefs’
     Functions implementing user-defined preferences.

‘set’
     Functions for creating and manipulating sets of unique values.

‘signal’
     Functions for signal processing applications.

‘sparse’
     Functions for handling sparse matrices.

‘specfun’
     Special functions such as ‘bessel’ or ‘factor’.

‘special-matrix’
     Functions that create special matrix forms such as Hilbert or
     Vandermonde matrices.

‘startup’
     Octave’s system-wide startup file.

‘statistics’
     Statistical functions.

‘strings’
     Miscellaneous string-handling functions.

‘testfun’
     Functions for performing unit tests on other functions.

‘time’
     Functions related to time and date processing.


File: octave.info,  Node: Errors and Warnings,  Next: Debugging,  Prev: Functions and Scripts,  Up: Top

12 Errors and Warnings
**********************

Octave includes several functions for printing error and warning
messages.  When you write functions that need to take special action
when they encounter abnormal conditions, you should print the error
messages using the functions described in this chapter.

   Since many of Octave’s functions use these functions, it is also
useful to understand them, so that errors and warnings can be handled.

* Menu:

* Handling Errors::
* Handling Warnings::


File: octave.info,  Node: Handling Errors,  Next: Handling Warnings,  Up: Errors and Warnings

12.1 Handling Errors
====================

An error is something that occurs when a program is in a state where it
doesn’t make sense to continue.  An example is when a function is called
with too few input arguments.  In this situation the function should
abort with an error message informing the user of the lacking input
arguments.

   Since an error can occur during the evaluation of a program, it is
very convenient to be able to detect that an error occurred, so that the
error can be fixed.  This is possible with the ‘try’ statement described
in *note The try Statement::.

* Menu:

* Raising Errors::
* Catching Errors::
* Recovering From Errors::


File: octave.info,  Node: Raising Errors,  Next: Catching Errors,  Up: Handling Errors

12.1.1 Raising Errors
---------------------

The most common use of errors is for checking input arguments to
functions.  The following example calls the ‘error’ function if the
function ‘f’ is called without any input arguments.

     function f (arg1)
       if (nargin == 0)
         error ("not enough input arguments");
       endif
     endfunction

   When the ‘error’ function is called, it prints the given message and
returns to the Octave prompt.  This means that no code following a call
to ‘error’ will be executed.

   It is also possible to assign an identification string to an error.
If an error has such an ID the user can catch this error as will be
described in the next section.  To assign an ID to an error, simply call
‘error’ with two string arguments, where the first is the identification
string, and the second is the actual error.  Note that error IDs are in
the format "NAMESPACE:ERROR-NAME". The namespace "Octave" is used for
Octave’s own errors.  Any other string is available as a namespace for
user’s own errors.

 -- : error (TEMPLATE, ...)
 -- : error (ID, TEMPLATE, ...)
     Display an error message and stop m-file execution.

     Format the optional arguments under the control of the template
     string TEMPLATE using the same rules as the ‘printf’ family of
     functions (*note Formatted Output::) and print the resulting
     message on the ‘stderr’ stream.  The message is prefixed by the
     character string ‘error: ’.

     Calling ‘error’ also sets Octave’s internal error state such that
     control will return to the top level without evaluating any further
     commands.  This is useful for aborting from functions or scripts.

     If the error message does not end with a newline character, Octave
     will print a traceback of all the function calls leading to the
     error.  For example, given the following function definitions:

          function f () g (); end
          function g () h (); end
          function h () nargin == 1 || error ("nargin != 1"); end

     calling the function ‘f’ will result in a list of messages that can
     help you to quickly find the exact location of the error:

          f ()
          error: nargin != 1
          error: called from:
          error:   h at line 1, column 27
          error:   g at line 1, column 15
          error:   f at line 1, column 15

     If the error message ends in a newline character, Octave will print
     the message but will not display any traceback messages as it
     returns control to the top level.  For example, modifying the error
     message in the previous example to end in a newline causes Octave
     to only print a single message:

          function h () nargin == 1 || error ("nargin != 1\n"); end
          f ()
          error: nargin != 1

     A null string ("") input to ‘error’ will be ignored and the code
     will continue running as if the statement were a NOP.  This is for
     compatibility with MATLAB.  It also makes it possible to write code
     such as

          err_msg = "";
          if (CONDITION 1)
            err_msg = "CONDITION 1 found";
          elseif (CONDITION2)
            err_msg = "CONDITION 2 found";
          ...
          endif
          error (err_msg);

     which will only stop execution if an error has been found.

     Implementation Note: For compatibility with MATLAB, escape
     sequences in TEMPLATE (e.g., "\n" => newline) are processed
     regardless of whether TEMPLATE has been defined with single quotes,
     as long as there are two or more input arguments.  To disable
     escape sequence expansion use a second backslash before the
     sequence (e.g., "\\n") or use the ‘regexptranslate’ function.

     See also: *note warning: XREFwarning, *note lasterror:
     XREFlasterror.

   Since it is common to use errors when there is something wrong with
the input to a function, Octave supports functions to simplify such
code.  When the ‘print_usage’ function is called, it reads the help text
of the function calling ‘print_usage’, and presents a useful error.  If
the help text is written in Texinfo it is possible to present an error
message that only contains the function prototypes as described by the
‘@deftypefn’ parts of the help text.  When the help text isn’t written
in Texinfo, the error message contains the entire help message.

   Consider the following function.

     ## -*- texinfo -*-
     ## @deftypefn {} f (@var{arg1})
     ## Function help text goes here...
     ## @end deftypefn
     function f (arg1)
       if (nargin == 0)
         print_usage ();
       endif
     endfunction

When it is called with no input arguments it produces the following
error.

     f ()

     ⊣  error: Invalid call to f.  Correct usage is:
     ⊣
     ⊣   -- f (ARG1)
     ⊣
     ⊣
     ⊣  Additional help for built-in functions and operators is
     ⊣  available in the online version of the manual.  Use the command
     ⊣  'doc <topic>' to search the manual index.
     ⊣
     ⊣  Help and information about Octave is also available on the WWW
     ⊣  at https://www.octave.org and via the help@octave.org
     ⊣  mailing list.

 -- : print_usage ()
 -- : print_usage (NAME)
     Print the usage message for the function NAME.

     When called with no input arguments the ‘print_usage’ function
     displays the usage message of the currently executing function.

     See also: *note help: XREFhelp.

 -- : beep ()
     Produce a beep from the speaker (or visual bell).

     This function sends the alarm character "\a" to the terminal.
     Depending on the user’s configuration this may produce an audible
     beep, a visual bell, or nothing at all.

     See also: *note puts: XREFputs, *note fputs: XREFfputs, *note
     printf: XREFprintf, *note fprintf: XREFfprintf.

 -- : VAL = beep_on_error ()
 -- : OLD_VAL = beep_on_error (NEW_VAL)
 -- : beep_on_error (NEW_VAL, "local")
     Query or set the internal variable that controls whether Octave
     will try to ring the terminal bell before printing an error
     message.

     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.


File: octave.info,  Node: Catching Errors,  Next: Recovering From Errors,  Prev: Raising Errors,  Up: Handling Errors

12.1.2 Catching Errors
----------------------

When an error occurs, it can be detected and handled using the ‘try’
statement as described in *note The try Statement::.  As an example, the
following piece of code counts the number of errors that occurs during a
‘for’ loop.

     number_of_errors = 0;
     for n = 1:100
       try
         ...
       catch
         number_of_errors++;
       end_try_catch
     endfor

   The above example treats all errors the same.  In many situations it
can however be necessary to discriminate between errors, and take
different actions depending on the error.  The ‘lasterror’ function
returns a structure containing information about the last error that
occurred.  As an example, the code above could be changed to count the
number of errors related to the ‘*’ operator.

     number_of_errors = 0;
     for n = 1:100
       try
         ...
       catch
         msg = lasterror.message;
         if (strfind (msg, "operator *"))
           number_of_errors++;
         endif
       end_try_catch
     endfor

Alternatively, the output of the ‘lasterror’ function can be found in a
variable indicated immediately after the ‘catch’ keyword, as in the
example below showing how to redirect an error as a warning:

     try
       ...
     catch err
       warning(err.identifier, err.message);
       ...
     end_try_catch

 -- : LASTERR = lasterror ()
 -- : lasterror (ERR)
 -- : lasterror ("reset")
     Query or set the last error message structure.

     When called without arguments, return a structure containing the
     last error message and other information related to this error.
     The elements of the structure are:

     ‘message’
          The text of the last error message

     ‘identifier’
          The message identifier of this error message

     ‘stack’
          A structure containing information on where the message
          occurred.  This may be an empty structure if the information
          cannot be obtained.  The fields of the structure are:

          ‘file’
               The name of the file where the error occurred

          ‘name’
               The name of function in which the error occurred

          ‘line’
               The line number at which the error occurred

          ‘column’
               An optional field with the column number at which the
               error occurred

     The last error structure may be set by passing a scalar structure,
     ERR, as input.  Any fields of ERR that match those above are set
     while any unspecified fields are initialized with default values.

     If ‘lasterror’ is called with the argument "reset", all fields are
     set to their default values.

     See also: *note lasterr: XREFlasterr, *note error: XREFerror, *note
     lastwarn: XREFlastwarn.

 -- : [MSG, MSGID] = lasterr ()
 -- : lasterr (MSG)
 -- : lasterr (MSG, MSGID)
     Query or set the last error message.

     When called without input arguments, return the last error message
     and message identifier.

     With one argument, set the last error message to MSG.

     With two arguments, also set the last message identifier.

     See also: *note lasterror: XREFlasterror, *note error: XREFerror,
     *note lastwarn: XREFlastwarn.

   The next example counts indexing errors.  The errors are caught using
the field identifier of the structure returned by the function
‘lasterror’.

     number_of_errors = 0;
     for n = 1:100
       try
         ...
       catch
         id = lasterror.identifier;
         if (strcmp (id, "Octave:invalid-indexing"))
           number_of_errors++;
         endif
       end_try_catch
     endfor

   The functions distributed with Octave can issue one of the following
errors.

‘Octave:invalid-context’
     Indicates the error was generated by an operation that cannot be
     executed in the scope from which it was called.  For example, the
     function ‘print_usage ()’ when called from the Octave prompt raises
     this error.

‘Octave:invalid-input-arg’
     Indicates that a function was called with invalid input arguments.

‘Octave:invalid-fun-call’
     Indicates that a function was called in an incorrect way, e.g.,
     wrong number of input arguments.

‘Octave:invalid-indexing’
     Indicates that a data-type was indexed incorrectly, e.g.,
     real-value index for arrays, nonexistent field of a structure.

‘Octave:bad-alloc’
     Indicates that memory couldn’t be allocated.

‘Octave:undefined-function’
     Indicates a call to a function that is not defined.  The function
     may exist but Octave is unable to find it in the search path.

   When an error has been handled it is possible to raise it again.
This can be useful when an error needs to be detected, but the program
should still abort.  This is possible using the ‘rethrow’ function.  The
previous example can now be changed to count the number of errors
related to the ‘*’ operator, but still abort if another kind of error
occurs.

     number_of_errors = 0;
     for n = 1:100
       try
         ...
       catch
         msg = lasterror.message;
         if (strfind (msg, "operator *"))
           number_of_errors++;
         else
           rethrow (lasterror);
         endif
       end_try_catch
     endfor

 -- : rethrow (ERR)
     Reissue a previous error as defined by ERR.

     ERR is a structure that must contain at least the "message" and
     "identifier" fields.  ERR can also contain a field "stack" that
     gives information on the assumed location of the error.  Typically
     ERR is returned from ‘lasterror’.

     See also: *note lasterror: XREFlasterror, *note lasterr:
     XREFlasterr, *note error: XREFerror.

 -- : ERR = errno ()
 -- : ERR = errno (VAL)
 -- : ERR = errno (NAME)
     Query or set the system-dependent variable errno.

     When called with no inputs, return the current value of errno.

     When called with a numeric input VAL, set the current value of
     errno to the specified value.  The previous value of errno is
     returned as ERR.

     When called with a character string NAME, return the numeric value
     of errno which corresponds to the specified error code.  If NAME is
     not a recognized error code then -1 is returned.

     See also: *note errno_list: XREFerrno_list.

 -- : errno_list ()
     Return a structure containing the system-dependent errno values.

     See also: *note errno: XREFerrno.


File: octave.info,  Node: Recovering From Errors,  Prev: Catching Errors,  Up: Handling Errors

12.1.3 Recovering From Errors
-----------------------------

Octave provides several ways of recovering from errors.  There are
‘try’/‘catch’ blocks, ‘unwind_protect’/‘unwind_protect_cleanup’ blocks,
and finally the ‘onCleanup’ command.

   The ‘onCleanup’ command associates an ordinary Octave variable (the
trigger) with an arbitrary function (the action).  Whenever the Octave
variable ceases to exist—whether due to a function return, an error, or
simply because the variable has been removed with ‘clear’—then the
assigned function is executed.

   The function can do anything necessary for cleanup such as closing
open file handles, printing an error message, or restoring global
variables to their initial values.  The last example is a very
convenient idiom for Octave code.  For example:

     function rand42
       old_state = rand ("state");
       restore_state = onCleanup (@() rand ("state", old_state));
       rand ("state", 42);
       ...
     endfunction  # rand generator state restored by onCleanup

 -- : OBJ = onCleanup (FUNCTION)
     Create a special object that executes a given function upon
     destruction.

     If the object is copied to multiple variables (or cell or struct
     array elements) or returned from a function, FUNCTION will be
     executed after clearing the last copy of the object.  Note that if
     multiple local onCleanup variables are created, the order in which
     they are called is unspecified.  For similar functionality *Note
     The unwind_protect Statement::.


File: octave.info,  Node: Handling Warnings,  Prev: Handling Errors,  Up: Errors and Warnings

12.2 Handling Warnings
======================

Like an error, a warning is issued when something unexpected happens.
Unlike an error, a warning doesn’t abort the currently running program.
A simple example of a warning is when a number is divided by zero.  In
this case Octave will issue a warning and assign the value ‘Inf’ to the
result.

     a = 1/0
          ⊣ warning: division by zero
          ⇒ a = Inf

* Menu:

* Issuing Warnings::
* Enabling and Disabling Warnings::


File: octave.info,  Node: Issuing Warnings,  Next: Enabling and Disabling Warnings,  Up: Handling Warnings

12.2.1 Issuing Warnings
-----------------------

It is possible to issue warnings from any code using the ‘warning’
function.  In its most simple form, the ‘warning’ function takes a
string describing the warning as its input argument.  As an example, the
following code controls if the variable ‘a’ is non-negative, and if not
issues a warning and sets ‘a’ to zero.

     a = -1;
     if (a < 0)
       warning ("'a' must be non-negative.  Setting 'a' to zero.");
       a = 0;
     endif
          ⊣ 'a' must be non-negative.  Setting 'a' to zero.

   Since warnings aren’t fatal to a running program, it is not possible
to catch a warning using the ‘try’ statement or something similar.  It
is however possible to access the last warning as a string using the
‘lastwarn’ function.

   It is also possible to assign an identification string to a warning.
If a warning has such an ID the user can enable and disable this warning
as will be described in the next section.  To assign an ID to a warning,
simply call ‘warning’ with two string arguments, where the first is the
identification string, and the second is the actual warning.  Note that
warning IDs are in the format "NAMESPACE:WARNING-NAME". The namespace
"Octave" is used for Octave’s own warnings.  Any other string is
available as a namespace for user’s own warnings.

 -- : warning (TEMPLATE, ...)
 -- : warning (ID, TEMPLATE, ...)
 -- : warning ("on", ID)
 -- : warning ("off", ID)
 -- : warning ("error", ID)
 -- : warning ("query", ID)
 -- : warning (STATE, ID, "local")
 -- : warning (WARNING_STRUCT)
 -- : WARNING_STRUCT = warning (...)
 -- : warning (STATE, MODE)

     Display a warning message or control the behavior of Octave’s
     warning system.

     The first call form uses a template TEMPLATE and optional
     additional arguments to display a message on the ‘stderr’ stream.
     The message is formatted using the same rules as the ‘printf’
     family of functions (*note Formatted Output::) and prefixed by the
     character string ‘warning: ’.  You should use this function when
     you want to notify the user of an unusual condition, but only when
     it makes sense for your program to go on.  For example:

          warning ("foo: maybe something wrong here");

     The optional warning identifier ID allows users to enable or
     disable warnings tagged by this identifier.  A message identifier
     is a string of the form "NAMESPACE:WARNING-NAME". Octave’s own
     warnings use the "Octave" namespace (*note warning_ids:
     XREFwarning_ids.).  For example:

          warning ("MyNameSpace:check-something",
                   "foo: maybe something wrong here");

     The second call form is meant to change and/or query the state of
     warnings.  The first input argument must be a string STATE ("on",
     "off", "error", or "query") followed by an optional warning
     identifier ID or "all" (default).

     The optional output argument WARNING_STRUCT is a structure or
     structure array with fields "state" and "identifier".  The STATE
     argument may have the following values:

     "on"|"off":
          Enable or disable the display of warnings identified by ID and
          optionally return their previous state STOUT.

     "error":
          Turn warnings identified by ID into errors and optionally
          return their previous state STOUT.

     "query":
          Return the current state of warnings identified by ID.

     A structure or structure array WARNING_STRUCT, with fields "state"
     and "identifier", may be given as an input to achieve equivalent
     results.  The following example shows how to temporarily disable a
     warning and then restore its original state:

          loglog (-1:10);
          ## Disable the previous warning and save its original state
          [~, id] = lastwarn ();
          warnstate = warning ("off", id);
          loglog (-1:10);
          ## Restore its original state
          warning (warnstate);

     If a final argument "local" is provided then the warning state will
     be set temporarily until the end of the current function.  Changes
     to warning states that are set locally affect the current function
     and all functions called from the current scope.  The previous
     warning state is restored on return from the current function.  The
     "local" option is ignored if used in the top-level workspace.

     With no input argument ‘warning ()’ is equivalent to ‘warning
     ("query", "all")’ except that in the absence of an output argument,
     the state of warnings is displayed on ‘stderr’.

     The level of verbosity of the warning system may also be controlled
     by two modes MODE:

     "backtrace":
          enable/disable the display of the stack trace after the
          warning message

     "verbose":
          enable/disable the display of additional information after the
          warning message

     In this case the STATE argument may only be "on" or "off".

     Implementation Note: For compatibility with MATLAB, escape
     sequences in TEMPLATE (e.g., "\n" => newline) are processed
     regardless of whether TEMPLATE has been defined with single quotes,
     as long as there are two or more input arguments.  To disable
     escape sequence expansion use a second backslash before the
     sequence (e.g., "\\n") or use the ‘regexptranslate’ function.

     See also: *note warning_ids: XREFwarning_ids, *note lastwarn:
     XREFlastwarn, *note error: XREFerror.

 -- : [MSG, MSGID] = lastwarn ()
 -- : lastwarn (MSG)
 -- : lastwarn (MSG, MSGID)
     Query or set the last warning message.

     When called without input arguments, return the last warning
     message and message identifier.

     With one argument, set the last warning message to MSG.

     With two arguments, also set the last message identifier.

     See also: *note warning: XREFwarning, *note lasterror:
     XREFlasterror, *note lasterr: XREFlasterr.

   The functions distributed with Octave can issue one of the following
warnings.

‘Octave:abbreviated-property-match’
     By default, the ‘Octave:abbreviated-property-match’ warning is
     enabled.

‘Octave:addpath-pkg’
     If the ‘Octave:addpath-pkg’ warning is enabled, Octave will warn
     when a package directory (i.e., +package_name) is added to the
     ‘path’.  Typically, only the parent directory which contains the
     package directory should be added to the load path.  By default,
     the ‘Octave:addpath-pkg’ warning is enabled.

‘Octave:array-as-logical’
     If the ‘Octave:array-as-logical’ warning is enabled, Octave will
     warn when an array of size greater than 1x1 is used as a truth
     value in an if, while or until statement.  By default, the
     ‘Octave:array-as-logical’ warning is disabled.

‘Octave:array-to-scalar’
     If the ‘Octave:array-to-scalar’ warning is enabled, Octave will
     warn when an implicit conversion from an array to a scalar value is
     attempted.  By default, the ‘Octave:array-to-scalar’ warning is
     disabled.

‘Octave:array-to-vector’
     If the ‘Octave:array-to-vector’ warning is enabled, Octave will
     warn when an implicit conversion from an array to a vector value is
     attempted.  By default, the ‘Octave:array-to-vector’ warning is
     disabled.

‘Octave:assign-as-truth-value’
     If the ‘Octave:assign-as-truth-value’ warning is enabled, a warning
     is issued for statements like

          if (s = t)
            ...

     since such statements are not common, and it is likely that the
     intent was to write

          if (s == t)
            ...

     instead.

     There are times when it is useful to write code that contains
     assignments within the condition of a ‘while’ or ‘if’ statement.
     For example, statements like

          while (c = getc ())
            ...

     are common in C programming.

     It is possible to avoid all warnings about such statements by
     disabling the ‘Octave:assign-as-truth-value’ warning, but that may
     also let real errors like

          if (x = 1)  # intended to test (x == 1)!
            ...

     slip by.

     In such cases, it is possible suppress errors for specific
     statements by writing them with an extra set of parentheses.  For
     example, writing the previous example as

          while ((c = getc ()))
            ...

     will prevent the warning from being printed for this statement,
     while allowing Octave to warn about other assignments used in
     conditional contexts.

     By default, the ‘Octave:assign-as-truth-value’ warning is enabled.

‘Octave:associativity-change’
     If the ‘Octave:associativity-change’ warning is enabled, Octave
     will warn about possible changes in the meaning of some code due to
     changes in associativity for some operators.  Associativity changes
     have typically been made for MATLAB compatibility.  By default, the
     ‘Octave:associativity-change’ warning is enabled.

‘Octave:autoload-relative-file-name’
     If the ‘Octave:autoload-relative-file-name’ is enabled, Octave will
     warn when parsing autoload() function calls with relative paths to
     function files.  This usually happens when using autoload() calls
     in PKG_ADD files, when the PKG_ADD file is not in the same
     directory as the .oct file referred to by the autoload() command.
     By default, the ‘Octave:autoload-relative-file-name’ warning is
     enabled.

‘Octave:built-in-variable-assignment’
     By default, the ‘Octave:built-in-variable-assignment’ warning is
     enabled.

‘Octave:deprecated-function’
     If the ‘Octave:deprecated-function’ warning is enabled, a warning
     is issued when Octave encounters a function that is obsolete and
     scheduled for removal from Octave.  By default, the
     ‘Octave:deprecated-function’ warning is enabled.

‘Octave:deprecated-keyword’
     If the ‘Octave:deprecated-keyword’ warning is enabled, a warning is
     issued when Octave encounters a keyword that is obsolete and
     scheduled for removal from Octave.  By default, the
     ‘Octave:deprecated-keyword’ warning is enabled.

‘Octave:deprecated-property’
     If the ‘Octave:deprecated-property’ warning is enabled, a warning
     is issued when Octave encounters a graphics property that is
     obsolete and scheduled for removal from Octave.  By default, the
     ‘Octave:deprecated-property’ warning is enabled.

‘Octave:divide-by-zero’
     If the ‘Octave:divide-by-zero’ warning is enabled, a warning is
     issued when Octave encounters a division by zero.  By default, the
     ‘Octave:divide-by-zero’ warning is enabled.

‘Octave:eigs:UnconvergedEigenvalues’
     If the ‘Octave:eigs:UnconvergedEigenvalues’ warning is enabled then
     the eigs function will issue a warning if the number of calculated
     eigenvalues is less than the number of requested eigenvalues.  By
     default, the ‘Octave:eigs:UnconvergedEigenvalues’ warning is
     enabled.

‘Octave:erase:chararray’
     If the ‘Octave:erase:chararray’ warning is enabled then the erase
     function will issue a warning if the input pattern is a character
     array rather than a string or cell array of strings.  By default,
     the ‘Octave:erase:chararray’ warning is enabled.

‘Octave:data-file-in-path’
     If the ‘Octave:data-file-in-path’ warning is enabled, a warning is
     issued when Octave does not find the target of a file operation
     such as ‘load’ or ‘fopen’ directly, but is able to locate the file
     in Octave’s search ‘path’ for files.  The warning could indicate
     that a different file target than the programmer intended is being
     used.  By default, the ‘Octave:data-file-in-path’ warning is
     enabled.

‘Octave:function-name-clash’
     If the ‘Octave:function-name-clash’ warning is enabled, a warning
     is issued when Octave finds that the name of a function defined in
     a function file differs from the name of the file.  (If the names
     disagree, the name declared inside the file is ignored.)  By
     default, the ‘Octave:function-name-clash’ warning is enabled.

‘Octave:future-time-stamp’
     If the ‘Octave:future-time-stamp’ warning is enabled, Octave will
     print a warning if it finds a function file with a time stamp that
     is in the future.  By default, the ‘Octave:future-time-stamp’
     warning is enabled.

‘Octave:glyph-render’
     By default, the ‘Octave:glyph-render’ warning is enabled.

‘Octave:imag-to-real’
     If the ‘Octave:imag-to-real’ warning is enabled, a warning is
     printed for implicit conversions of complex numbers to real
     numbers.  By default, the ‘Octave:imag-to-real’ warning is
     disabled.

‘Octave:language-extension’
     Print warnings when using features that are unique to the Octave
     language and that may still be missing in MATLAB.  By default, the
     ‘Octave:language-extension’ warning is disabled.  The
     ‘--traditional’ or ‘--braindead’ startup options for Octave may
     also be of use, *note Command Line Options::.

‘Octave:logical-conversion’
     By default, the ‘Octave:logical-conversion’ warning is enabled.

‘Octave:lu:sparse_input’
     If the ‘Octave:lu:sparse_input’ warning is enabled, Octave will
     warn when the lu function is called with a sparse input and less
     than four output arguments.  In this case, sparsity-preserving
     column permutations are not performed and the result may be
     inaccurate.  By default, the ‘Octave:lu:sparse_input’ warning is
     enabled.

‘Octave:missing-glyph’
     By default, the ‘Octave:missing-glyph’ warning is enabled.

‘Octave:missing-semicolon’
     If the ‘Octave:missing-semicolon’ warning is enabled, Octave will
     warn when statements in function definitions don’t end in
     semicolons.  By default the ‘Octave:missing-semicolon’ warning is
     disabled.

‘Octave:mixed-string-concat’
     If the ‘Octave:mixed-string-concat’ warning is enabled, print a
     warning when concatenating a mixture of double and single quoted
     strings.  By default, the ‘Octave:mixed-string-concat’ warning is
     disabled.

‘Octave:nearly-singular-matrix’
‘Octave:singular-matrix’
     By default, the ‘Octave:nearly-singular-matrix’ and
     ‘Octave:singular-matrix’ warnings are enabled.

‘Octave:neg-dim-as-zero’
     If the ‘Octave:neg-dim-as-zero’ warning is enabled, print a warning
     for expressions like

          eye (-1)

     By default, the ‘Octave:neg-dim-as-zero’ warning is disabled.

‘Octave:nested-functions-coerced’
     By default, the ‘Octave:nested-functions-coerced’ warning is
     enabled.

‘Octave:noninteger-range-as-index’
     By default, the ‘Octave:noninteger-range-as-index’ warning is
     enabled.

‘Octave:num-to-str’
     If the ‘Octave:num-to-str’ warning is enable, a warning is printed
     for implicit conversions of numbers to their ASCII character
     equivalents when strings are constructed using a mixture of strings
     and numbers in matrix notation.  For example,

          [ "f", 111, 111 ]
          ⇒ "foo"

     elicits a warning if the ‘Octave:num-to-str’ warning is enabled.
     By default, the ‘Octave:num-to-str’ warning is enabled.

‘Octave:possible-matlab-short-circuit-operator’
     If the ‘Octave:possible-matlab-short-circuit-operator’ warning is
     enabled, Octave will warn about using the not short circuiting
     operators ‘&’ and ‘|’ inside ‘if’ or ‘while’ conditions.  They
     normally never short circuit, but they do short circuit when used
     in a condition.  By default, the
     ‘Octave:possible-matlab-short-circuit-operator’ warning is enabled.

‘Octave:precedence-change’
     If the ‘Octave:precedence-change’ warning is enabled, Octave will
     warn about possible changes in the meaning of some code due to
     changes in precedence for some operators.  Precedence changes have
     typically been made for MATLAB compatibility.  By default, the
     ‘Octave:precedence-change’ warning is enabled.

‘Octave:recursive-path-search’
     By default, the ‘Octave:recursive-path-search’ warning is enabled.

‘Octave:remove-init-dir’
     The ‘path’ function changes the search path that Octave uses to
     find functions.  It is possible to set the path to a value which
     excludes Octave’s own built-in functions.  If the
     ‘Octave:remove-init-dir’ warning is enabled then Octave will warn
     when the ‘path’ function has been used in a way that may render
     Octave unworkable.  By default, the ‘Octave:remove-init-dir’
     warning is enabled.

‘Octave:reload-forces-clear’
     If several functions have been loaded from the same file, Octave
     must clear all the functions before any one of them can be
     reloaded.  If the ‘Octave:reload-forces-clear’ warning is enabled,
     Octave will warn you when this happens, and print a list of the
     additional functions that it is forced to clear.  By default, the
     ‘Octave:reload-forces-clear’ warning is enabled.

‘Octave:resize-on-range-error’
     If the ‘Octave:resize-on-range-error’ warning is enabled, print a
     warning when a matrix is resized by an indexed assignment with
     indices outside the current bounds.  By default, the
     ‘Octave:resize-on-range-error’ warning is disabled.

‘Octave:separator-insert’
     Print warning if commas or semicolons might be inserted
     automatically in literal matrices.  By default, the
     ‘Octave:separator-insert’ warning is disabled.

‘Octave:shadowed-function’
     By default, the ‘Octave:shadowed-function’ warning is enabled.

‘Octave:single-quote-string’
     Print warning if a single quote character is used to introduce a
     string constant.  By default, the ‘Octave:single-quote-string’
     warning is disabled.

‘Octave:sqrtm:SingularMatrix’
     By default, the ‘Octave:sqrtm:SingularMatrix’ warning is enabled.

‘Octave:str-to-num’
     If the ‘Octave:str-to-num’ warning is enabled, a warning is printed
     for implicit conversions of strings to their numeric ASCII
     equivalents.  For example,

          "abc" + 0
          ⇒ 97 98 99

     elicits a warning if the ‘Octave:str-to-num’ warning is enabled.
     By default, the ‘Octave:str-to-num’ warning is disabled.

‘Octave:variable-switch-label’
     If the ‘Octave:variable-switch-label’ warning is enabled, Octave
     will print a warning if a switch label is not a constant or
     constant expression.  By default, the
     ‘Octave:variable-switch-label’ warning is disabled.


File: octave.info,  Node: Enabling and Disabling Warnings,  Prev: Issuing Warnings,  Up: Handling Warnings

12.2.2 Enabling and Disabling Warnings
--------------------------------------

The ‘warning’ function also allows you to control which warnings are
actually printed to the screen.  If the ‘warning’ function is called
with a string argument that is either "on" or "off" all warnings will be
enabled or disabled.

   It is also possible to enable and disable individual warnings through
their string identifications.  The following code will issue a warning

     warning ("example:non-negative-variable",
              "'a' must be non-negative.  Setting 'a' to zero.");

while the following won’t issue a warning

     warning ("off", "example:non-negative-variable");
     warning ("example:non-negative-variable",
              "'a' must be non-negative.  Setting 'a' to zero.");


File: octave.info,  Node: Debugging,  Next: Input and Output,  Prev: Errors and Warnings,  Up: Top

13 Debugging
************

Octave includes a built-in debugger to aid in the development of
scripts.  This can be used to interrupt the execution of an Octave
script at a certain point, or when certain conditions are met.  Once
execution has stopped, and debug mode is entered, the symbol table at
the point where execution has stopped can be examined and modified to
check for errors.

   The normal command-line editing and history functions are available
in debug mode.

* Menu:

* Entering Debug Mode::
* Leaving Debug Mode::
* Breakpoints::
* Debug Mode::
* Call Stack::
* Profiling::
* Profiler Example::


File: octave.info,  Node: Entering Debug Mode,  Next: Leaving Debug Mode,  Up: Debugging

13.1 Entering Debug Mode
========================

There are two basic means of interrupting the execution of an Octave
script.  These are breakpoints (*note Breakpoints::), discussed in the
next section, and interruption based on some condition.

   Octave supports three means to stop execution based on the values set
in the functions ‘debug_on_interrupt’, ‘debug_on_warning’, and
‘debug_on_error’.

 -- : VAL = debug_on_interrupt ()
 -- : OLD_VAL = debug_on_interrupt (NEW_VAL)
 -- : debug_on_interrupt (NEW_VAL, "local")
     Query or set the internal variable that controls whether Octave
     will try to enter debugging mode when it receives an interrupt
     signal (typically generated with ‘C-c’).

     If a second interrupt signal is received before reaching the
     debugging mode, a normal interrupt will occur.

     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 debug_on_error: XREFdebug_on_error, *note
     debug_on_warning: XREFdebug_on_warning.

 -- : VAL = debug_on_warning ()
 -- : OLD_VAL = debug_on_warning (NEW_VAL)
 -- : debug_on_warning (NEW_VAL, "local")
     Query or set the internal variable that controls whether Octave
     will try to enter the debugger when a warning is encountered.

     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 debug_on_error: XREFdebug_on_error, *note
     debug_on_interrupt: XREFdebug_on_interrupt.

 -- : VAL = debug_on_error ()
 -- : OLD_VAL = debug_on_error (NEW_VAL)
 -- : debug_on_error (NEW_VAL, "local")
     Query or set the internal variable that controls whether Octave
     will try to enter the debugger when an error is encountered.

     This will also inhibit printing of the normal traceback message
     (you will only see the top-level error message).

     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 debug_on_warning: XREFdebug_on_warning, *note
     debug_on_interrupt: XREFdebug_on_interrupt.


File: octave.info,  Node: Leaving Debug Mode,  Next: Breakpoints,  Prev: Entering Debug Mode,  Up: Debugging

13.2 Leaving Debug Mode
=======================

Use either ‘dbcont’ or ‘return’ to leave the debug mode and continue the
normal execution of the script.

 -- : dbcont
     Leave command-line debugging mode and continue code execution
     normally.

     See also: *note dbstep: XREFdbstep, *note dbquit: XREFdbquit.

   To quit debug mode and return directly to the prompt without
executing any additional code use ‘dbquit’.

 -- : dbquit
     Quit debugging mode immediately without further code execution and
     return to the Octave prompt.

     See also: *note dbcont: XREFdbcont, *note dbstep: XREFdbstep.

   Finally, typing ‘exit’ or ‘quit’ at the debug prompt will result in
Octave terminating normally.


File: octave.info,  Node: Breakpoints,  Next: Debug Mode,  Prev: Leaving Debug Mode,  Up: Debugging

13.3 Breakpoints
================

Breakpoints can be set in any m-file function by using the ‘dbstop’
function.

 -- : dbstop FUNC
 -- : dbstop FUNC LINE
 -- : dbstop FUNC LINE1 LINE2 ...
 -- : dbstop LINE1 ...
 -- : dbstop in FUNC
 -- : dbstop in FUNC at LINE
 -- : dbstop in FUNC at LINE if "CONDITION"
 -- : dbstop if EVENT
 -- : dbstop if EVENT ID
 -- : dbstop (BP_STRUCT)
 -- : RLINE = dbstop ...

     Set breakpoints for the built-in debugger.

     FUNC is the name of a function on the current ‘path’.  When already
     in debug mode the FUNC argument can be omitted and the current
     function will be used.  Breakpoints at subfunctions are set with
     the scope operator ‘>’.  For example, If ‘file.m’ has a subfunction
     ‘func2’, then a breakpoint in ‘func2’ can be specified by
     ‘file>func2’.

     LINE is the line number at which to break.  If LINE is not
     specified, it defaults to the first executable line in the file
     ‘func.m’.  Multiple lines can be specified in a single command;
     when function syntax is used, the lines may also be passed as a
     single vector argument (‘[LINE1, LINE2, ...]’).

     CONDITION is any Octave expression that can be evaluated in the
     code context that exists at the breakpoint.  When the breakpoint is
     encountered, CONDITION will be evaluated, and execution will stop
     if CONDITION is true.  If CONDITION cannot be evaluated, for
     example because it refers to an undefined variable, an error will
     be thrown.  Expressions with side effects (such as ‘y++ > 1’) will
     alter variables, and should generally be avoided.  Conditions
     containing quotes (‘"’, ‘'’) or comment characters (‘#’, ‘%’) must
     be enclosed in quotes.  (This does not apply to conditions entered
     from the editor’s context menu.)  For example:

          dbstop in strread at 209 if 'any (format == "%f")'

     The form specifying EVENT does not cause a specific breakpoint at a
     given function and line number.  Instead it causes debug mode to be
     entered when certain unexpected events are encountered.  Possible
     values are

     ‘error’
          Stop when an error is reported.  This is equivalent to
          specifying both ‘debug_on_error (true)’ and
          ‘debug_on_interrupt (true)’.

     ‘caught error’
          Stop when an error is caught by a try-catch block (not yet
          implemented).

     ‘interrupt’
          Stop when an interrupt (‘Ctrl-C’) occurs.

     ‘naninf’
          Stop when code returns a non-finite value (not yet
          implemented).

     ‘warning’
          Stop when a warning is reported.  This is equivalent to
          specifying ‘debug_on_warning (true)’.

     The events ‘error’, ‘caught error’, and ‘warning’ can all be
     followed by a string specifying an error ID or warning ID.  If that
     is done, only errors with the specified ID will cause execution to
     stop.  To stop on one of a set of IDs, multiple ‘dbstop’ commands
     must be issued.

     Breakpoints and events can be removed using the ‘dbclear’ command
     with the same syntax.

     It is possible to save all breakpoints and restore them at once by
     issuing the commands ‘bp_state = dbstatus; ...; dbstop (bp_state)’.

     The optional output RLINE is the real line number where the
     breakpoint was set.  This can differ from the specified line if the
     line is not executable.  For example, if a breakpoint attempted on
     a blank line then Octave will set the real breakpoint at the next
     executable line.

     When a file is re-parsed, such as when it is modified outside the
     GUI, all breakpoints within the file are cleared.

     See also: *note dbclear: XREFdbclear, *note dbstatus: XREFdbstatus,
     *note dbstep: XREFdbstep, *note debug_on_error: XREFdebug_on_error,
     *note debug_on_warning: XREFdebug_on_warning, *note
     debug_on_interrupt: XREFdebug_on_interrupt.

Breakpoints in class methods are also supported (e.g., ‘dbstop
("@class/method")’).  However, breakpoints cannot be set in built-in
functions (e.g., ‘sin’, etc.) or dynamically loaded functions (i.e.,
oct-files).

   To set a breakpoint immediately upon entering a function use line
number 1, or omit the line number entirely and just give the function
name.  When setting the breakpoint Octave will ignore the leading
comment block, and the breakpoint will be set on the first executable
statement in the function.  For example:

     dbstop ("asind", 1)
     ⇒ 29

Note that the return value of ‘29’ means that the breakpoint was
effectively set to line 29.  The status of breakpoints in a function can
be queried with ‘dbstatus’.

 -- : dbstatus
 -- : dbstatus FUNC
 -- : BP_LIST = dbstatus ...
     Report the location of active breakpoints.

     When called with no input or output arguments, print the list of
     all functions with breakpoints and the line numbers where those
     breakpoints are set.

     If a function name FUNC is specified then only report breakpoints
     for the named function and its subfunctions.

     The optional return argument BP_LIST is a struct array with the
     following fields.

     name
          The name of the function with a breakpoint.  A subfunction,
          say ‘func2’ within an m-file, say ‘file.m’, is specified as
          ‘file>func2’.

     file
          The name of the m-file where the function code is located.

     line
          The line number with the breakpoint.

     cond
          The condition that must be satisfied for the breakpoint to be
          active, or the empty string for unconditional breakpoints.

     If ‘dbstop if error’ is true but no explicit IDs are specified, the
     return value will have an empty field called "errs".  If IDs are
     specified, the ‘errs’ field will have one row per ID.  If ‘dbstop
     if error’ is false, there is no "errs" field.  The "warn" field is
     set similarly by ‘dbstop if warning’.

     See also: *note dbstop: XREFdbstop, *note dbclear: XREFdbclear,
     *note dbwhere: XREFdbwhere, *note dblist: XREFdblist, *note
     dbstack: XREFdbstack.

Reusing the previous example, ‘dbstatus ("asind")’ will return 29.  The
breakpoints listed can then be cleared with the ‘dbclear’ function.

 -- : dbclear FUNC
 -- : dbclear FUNC LINE
 -- : dbclear FUNC LINE1 LINE2 ...
 -- : dbclear LINE ...
 -- : dbclear all
 -- : dbclear in FUNC
 -- : dbclear in FUNC at LINE
 -- : dbclear if EVENT
 -- : dbclear ("FUNC")
 -- : dbclear ("FUNC", LINE)
 -- : dbclear ("FUNC", LINE1, LINE2, ...)
 -- : dbclear ("FUNC", LINE1, ...)
 -- : dbclear (LINE, ...)
 -- : dbclear ("all")
     Delete a breakpoint at line number LINE in the function FUNC.

     Arguments are

     FUNC
          Function name as a string variable.  When already in debug
          mode this argument can be omitted and the current function
          will be used.

     LINE
          Line number from which to remove a breakpoint.  Multiple lines
          may be given as separate arguments or as a vector.

     EVENT
          An event such as ‘error’, ‘interrupt’, or ‘warning’ (*note
          dbstop: XREFdbstop. for details).

     When called without a line number specification all breakpoints in
     the named function are cleared.

     If the requested line is not a breakpoint no action is performed.

     The special keyword "all" will clear all breakpoints from all
     files.

     See also: *note dbstop: XREFdbstop, *note dbstatus: XREFdbstatus,
     *note dbwhere: XREFdbwhere.


   A breakpoint may also be set in a subfunction.  For example, if a
file contains the functions

     function y = func1 (x)
       y = func2 (x);
     endfunction
     function y = func2 (x)
       y = x + 1;
     endfunction

then a breakpoint can be set at the start of the subfunction directly
with

     dbstop func1>func2
     ⇒ 5

   Note that ‘>’ is the character that distinguishes subfunctions from
the m-file containing them.

   Another simple way of setting a breakpoint in an Octave script is the
use of the ‘keyboard’ function.

 -- : keyboard ()
 -- : keyboard ("PROMPT")
     Stop m-file execution and enter debug mode.

     When the ‘keyboard’ function is executed, Octave prints a prompt
     and waits for user input.  The input strings are then evaluated and
     the results are printed.  This makes it possible to examine the
     values of variables within a function, and to assign new values if
     necessary.  To leave the prompt and return to normal execution type
     ‘return’ or ‘dbcont’.  The ‘keyboard’ function does not return an
     exit status.

     If ‘keyboard’ is invoked without arguments, a default prompt of
     ‘debug> ’ is used.

     See also: *note dbstop: XREFdbstop, *note dbcont: XREFdbcont, *note
     dbquit: XREFdbquit.

The ‘keyboard’ function is placed in a script at the point where the
user desires that the execution be stopped.  It automatically sets the
running script into the debug mode.


File: octave.info,  Node: Debug Mode,  Next: Call Stack,  Prev: Breakpoints,  Up: Debugging

13.4 Debug Mode
===============

There are three additional support functions that allow the user to find
out where in the execution of a script Octave entered the debug mode,
and to print the code in the script surrounding the point where Octave
entered debug mode.

 -- : dbwhere
     In debugging mode, report the current file and line number where
     execution is stopped.

     See also: *note dbstack: XREFdbstack, *note dblist: XREFdblist,
     *note dbstatus: XREFdbstatus, *note dbcont: XREFdbcont, *note
     dbstep: XREFdbstep, *note dbup: XREFdbup, *note dbdown: XREFdbdown.

 -- : dbtype
 -- : dbtype LINENO
 -- : dbtype STARTL:ENDL
 -- : dbtype STARTL:END
 -- : dbtype FUNC
 -- : dbtype FUNC LINENO
 -- : dbtype FUNC STARTL:ENDL
 -- : dbtype FUNC STARTL:END
     Display a script file with line numbers.

     When called with no arguments in debugging mode, display the script
     file currently being debugged.

     An optional range specification can be used to list only a portion
     of the file.  The special keyword "end" is a valid line number
     specification for the last line of the file.

     When called with the name of a function, list that script file with
     line numbers.

     See also: *note dblist: XREFdblist, *note dbwhere: XREFdbwhere,
     *note dbstatus: XREFdbstatus, *note dbstop: XREFdbstop.

 -- : dblist
 -- : dblist N
     In debugging mode, list N lines of the function being debugged
     centered around the current line to be executed.

     If unspecified N defaults to 10 (+/- 5 lines)

     See also: *note dbwhere: XREFdbwhere, *note dbtype: XREFdbtype,
     *note dbstack: XREFdbstack.

   You may also use ‘isdebugmode’ to determine whether the debugger is
currently active.

 -- : isdebugmode ()
     Return true if in debugging mode, otherwise false.

     See also: *note dbwhere: XREFdbwhere, *note dbstack: XREFdbstack,
     *note dbstatus: XREFdbstatus.

   Debug mode also allows single line stepping through a function using
the command ‘dbstep’.

 -- : dbstep
 -- : dbstep N
 -- : dbstep in
 -- : dbstep out
 -- : dbnext ...
     In debugging mode, execute the next N lines of code.

     If N is omitted, execute the next single line of code.  If the next
     line of code is itself defined in terms of an m-file remain in the
     existing function.

     Using ‘dbstep in’ will cause execution of the next line to step
     into any m-files defined on the next line.

     Using ‘dbstep out’ will cause execution to continue until the
     current function returns.

     ‘dbnext’ is an alias for ‘dbstep’.

     See also: *note dbcont: XREFdbcont, *note dbquit: XREFdbquit.

   When in debug mode the <RETURN> key will execute the last entered
command.  This is useful, for example, after hitting a breakpoint and
entering ‘dbstep’ once.  After that, one can advance line by line
through the code with only a single key stroke.


File: octave.info,  Node: Call Stack,  Next: Profiling,  Prev: Debug Mode,  Up: Debugging

13.5 Call Stack
===============

The function being debugged may be the leaf node of a series of function
calls.  After examining values in the current subroutine it may turn out
that the problem occurred in earlier pieces of code.  Use ‘dbup’ and
‘dbdown’ to move up and down through the series of function calls to
locate where variables first took on the wrong values.  ‘dbstack’ shows
the entire series of function calls and at what level debugging is
currently taking place.

 -- : dbstack
 -- : dbstack N
 -- : dbstack -COMPLETENAMES
 -- : [STACK, IDX] = dbstack (...)
     Display or return current debugging function stack information.

     With optional argument N, omit the N innermost stack frames.

     Although accepted, the argument -COMPLETENAMES is silently ignored.
     Octave always returns absolute filenames.

     The arguments N and -COMPLETENAMES can be both specified in any
     order.

     The optional return argument STACK is a struct array with the
     following fields:

     file
          The name of the m-file where the function code is located.

     name
          The name of the function with a breakpoint.

     line
          The line number of an active breakpoint.

     column
          The column number of the line where the breakpoint begins.

     scope
          Undocumented.

     context
          Undocumented.

     The return argument IDX specifies which element of the STACK struct
     array is currently active.

     See also: *note dbup: XREFdbup, *note dbdown: XREFdbdown, *note
     dbwhere: XREFdbwhere, *note dblist: XREFdblist, *note dbstatus:
     XREFdbstatus.

 -- : dbup
 -- : dbup N
     In debugging mode, move up the execution stack N frames.

     If N is omitted, move up one frame.

     See also: *note dbstack: XREFdbstack, *note dbdown: XREFdbdown.

 -- : dbdown
 -- : dbdown N
     In debugging mode, move down the execution stack N frames.

     If N is omitted, move down one frame.

     See also: *note dbstack: XREFdbstack, *note dbup: XREFdbup.


File: octave.info,  Node: Profiling,  Next: Profiler Example,  Prev: Call Stack,  Up: Debugging

13.6 Profiling
==============

Octave supports profiling of code execution on a per-function level.  If
profiling is enabled, each call to a function (supporting built-ins,
operators, functions in oct- and mex-files, user-defined functions in
Octave code and anonymous functions) is recorded while running Octave
code.  After that, this data can aid in analyzing the code behavior, and
is in particular helpful for finding “hot spots” in the code which use
up a lot of computation time and are the best targets to spend
optimization efforts on.

   The main command for profiling is ‘profile’, which can be used to
start or stop the profiler and also to query collected data afterwards.
The data is returned in an Octave data structure which can then be
examined or further processed by other routines or tools.

 -- : profile on
 -- : profile off
 -- : profile resume
 -- : profile clear
 -- : S = profile ("status")
 -- : T = profile ("info")
     Control the built-in profiler.

     ‘profile on’
          Start the profiler, clearing all previously collected data if
          there is any.

     ‘profile off’
          Stop profiling.  The collected data can later be retrieved and
          examined with ‘T = profile ("info")’.

     ‘profile clear’
          Clear all collected profiler data.

     ‘profile resume’
          Restart profiling without clearing the old data.  All newly
          collected statistics are added to the existing ones.

     ‘S = profile ("status")’
          Return a structure with information about the current status
          of the profiler.  At the moment, the only field is
          ‘ProfilerStatus’ which is either "on" or "off".

     ‘T = profile ("info")’
          Return the collected profiling statistics in the structure T.
          The flat profile is returned in the field ‘FunctionTable’
          which is an array of structures, each entry corresponding to a
          function which was called and for which profiling statistics
          are present.  In addition, the field ‘Hierarchical’ contains
          the hierarchical call tree.  Each node has an index into the
          ‘FunctionTable’ identifying the function it corresponds to as
          well as data fields for number of calls and time spent at this
          level in the call tree.

          See also: *note profshow: XREFprofshow, *note profexplore:
          XREFprofexplore.

   An easy way to get an overview over the collected data is ‘profshow’.
This function takes the profiler data returned by ‘profile’ as input and
prints a flat profile, for instance:

      Function Attr     Time (s)        Calls
     ----------------------------------------
        >myfib    R        2.195        13529
     binary <=             0.061        13529
      binary -             0.050        13528
      binary +             0.026         6764

   This shows that most of the run time was spent executing the function
‘myfib’, and some minor proportion evaluating the listed binary
operators.  Furthermore, it is shown how often the function was called
and the profiler also records that it is recursive.

 -- : profshow (DATA)
 -- : profshow (DATA, N)
 -- : profshow ()
 -- : profshow (N)
     Display flat per-function profiler results.

     Print out profiler data (execution time, number of calls) for the
     most critical N functions.  The results are sorted in descending
     order by the total time spent in each function.  If N is
     unspecified it defaults to 20.

     The input DATA is the structure returned by ‘profile ("info")’.  If
     unspecified, ‘profshow’ will use the current profile dataset.

     The attribute column displays ‘R’ for recursive functions, and is
     blank for all other function types.

     See also: *note profexplore: XREFprofexplore, *note profile:
     XREFprofile.

 -- : profexport (DIR)
 -- : profexport (DIR, DATA)
 -- : profexport (DIR, NAME)
 -- : profexport (DIR, NAME, DATA)

     Export profiler data as HTML.

     Export the profiling data in DATA into a series of HTML files in
     the folder DIR.  The initial file will be ‘DATA/index.html’.

     If NAME is specified, it must be a string that contains a “name”
     for the profile being exported.  This name is included in the HTML.

     The input DATA is the structure returned by ‘profile ("info")’.  If
     unspecified, ‘profexport’ will use the current profile dataset.

     See also: *note profshow: XREFprofshow, *note profexplore:
     XREFprofexplore, *note profile: XREFprofile.

 -- : profexplore ()
 -- : profexplore (DATA)
     Interactively explore hierarchical profiler output.

     Assuming DATA is the structure with profile data returned by
     ‘profile ("info")’, this command opens an interactive prompt that
     can be used to explore the call-tree.  Type ‘help’ to get a list of
     possible commands.  If DATA is omitted, ‘profile ("info")’ is
     called and used in its place.

     See also: *note profile: XREFprofile, *note profshow: XREFprofshow.


File: octave.info,  Node: Profiler Example,  Prev: Profiling,  Up: Debugging

13.7 Profiler Example
=====================

Below, we will give a short example of a profiler session.  *Note
Profiling::, for the documentation of the profiler functions in detail.
Consider the code:

     global N A;

     N = 300;
     A = rand (N, N);

     function xt = timesteps (steps, x0, expM)
       global N;

       if (steps == 0)
         xt = NA (N, 0);
       else
         xt = NA (N, steps);
         x1 = expM * x0;
         xt(:, 1) = x1;
         xt(:, 2 : end) = timesteps (steps - 1, x1, expM);
       endif
     endfunction

     function foo ()
       global N A;

       initial = @(x) sin (x);
       x0 = (initial (linspace (0, 2 * pi, N)))';

       expA = expm (A);
       xt = timesteps (100, x0, expA);
     endfunction

     function fib = bar (N)
       if (N <= 2)
         fib = 1;
       else
         fib = bar (N - 1) + bar (N - 2);
       endif
     endfunction

   If we execute the two main functions, we get:

     tic; foo; toc;
     ⇒ Elapsed time is 2.37338 seconds.

     tic; bar (20); toc;
     ⇒ Elapsed time is 2.04952 seconds.

   But this does not give much information about where this time is
spent; for instance, whether the single call to ‘expm’ is more expensive
or the recursive time-stepping itself.  To get a more detailed picture,
we can use the profiler.

     profile on;
     foo;
     profile off;

     data = profile ("info");
     profshow (data, 10);

   This prints a table like:

        #  Function Attr     Time (s)        Calls
     ---------------------------------------------
        7      expm             1.034            1
        3  binary *             0.823          117
       41  binary \             0.188            1
       38  binary ^             0.126            2
       43 timesteps    R        0.111          101
       44        NA             0.029          101
       39  binary +             0.024            8
       34      norm             0.011            1
       40  binary -             0.004          101
       33   balance             0.003            1

   The entries are the individual functions which have been executed
(only the 10 most important ones), together with some information for
each of them.  The entries like ‘binary *’ denote operators, while other
entries are ordinary functions.  They include both built-ins like ‘expm’
and our own routines (for instance ‘timesteps’).  From this profile, we
can immediately deduce that ‘expm’ uses up the largest proportion of the
processing time, even though it is only called once.  The second
expensive operation is the matrix-vector product in the routine
‘timesteps’.  (1)

   Timing, however, is not the only information available from the
profile.  The attribute column shows us that ‘timesteps’ calls itself
recursively.  This may not be that remarkable in this example (since
it’s clear anyway), but could be helpful in a more complex setting.  As
to the question of why is there a ‘binary \’ in the output, we can
easily shed some light on that too.  Note that ‘data’ is a structure
array (*note Structure Arrays::) which contains the field
‘FunctionTable’.  This stores the raw data for the profile shown.  The
number in the first column of the table gives the index under which the
shown function can be found there.  Looking up ‘data.FunctionTable(41)’
gives:

       scalar structure containing the fields:

         FunctionName = binary \
         TotalTime =  0.18765
         NumCalls =  1
         IsRecursive = 0
         Parents =  7
         Children = [](1x0)

   Here we see the information from the table again, but have additional
fields ‘Parents’ and ‘Children’.  Those are both arrays, which contain
the indices of functions which have directly called the function in
question (which is entry 7, ‘expm’, in this case) or been called by it
(no functions).  Hence, the backslash operator has been used internally
by ‘expm’.

   Now let’s take a look at ‘bar’.  For this, we start a fresh profiling
session (‘profile on’ does this; the old data is removed before the
profiler is restarted):

     profile on;
     bar (20);
     profile off;

     profshow (profile ("info"));

   This gives:

        #            Function Attr     Time (s)        Calls
     -------------------------------------------------------
        1                 bar    R        2.091        13529
        2           binary <=             0.062        13529
        3            binary -             0.042        13528
        4            binary +             0.023         6764
        5             profile             0.000            1
        8               false             0.000            1
        6              nargin             0.000            1
        7           binary !=             0.000            1
        9 __profiler_enable__             0.000            1

   Unsurprisingly, ‘bar’ is also recursive.  It has been called 13,529
times in the course of recursively calculating the Fibonacci number in a
suboptimal way, and most of the time was spent in ‘bar’ itself.

   Finally, let’s say we want to profile the execution of both ‘foo’ and
‘bar’ together.  Since we already have the run-time data collected for
‘bar’, we can restart the profiler without clearing the existing data
and collect the missing statistics about ‘foo’.  This is done by:

     profile resume;
     foo;
     profile off;

     profshow (profile ("info"), 10);

   As you can see in the table below, now we have both profiles mixed
together.

        #  Function Attr     Time (s)        Calls
     ---------------------------------------------
        1       bar    R        2.091        13529
       16      expm             1.122            1
       12  binary *             0.798          117
       46  binary \             0.185            1
       45  binary ^             0.124            2
       48 timesteps    R        0.115          101
        2 binary <=             0.062        13529
        3  binary -             0.045        13629
        4  binary +             0.041         6772
       49        NA             0.036          101

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

   (1) We only know it is the binary multiplication operator, but
fortunately this operator appears only at one place in the code and thus
we know which occurrence takes so much time.  If there were multiple
places, we would have to use the hierarchical profile to find out the
exact place which uses up the time which is not covered in this example.


File: octave.info,  Node: Input and Output,  Next: Plotting,  Prev: Debugging,  Up: Top

14 Input and Output
*******************

Octave supports several ways of reading and writing data to or from the
prompt or a file.  The simplest functions for data Input and Output
(I/O) are easy to use, but only provide limited control of how data is
processed.  For more control, a set of functions modeled after the C
standard library are also provided by Octave.

* Menu:

* Basic Input and Output::
* C-Style I/O Functions::


File: octave.info,  Node: Basic Input and Output,  Next: C-Style I/O Functions,  Up: Input and Output

14.1 Basic Input and Output
===========================

* Menu:

* Terminal Output::
* Terminal Input::
* Simple File I/O::


File: octave.info,  Node: Terminal Output,  Next: Terminal Input,  Up: Basic Input and Output

14.1.1 Terminal Output
----------------------

Since Octave normally prints the value of an expression as soon as it
has been evaluated, the simplest of all I/O functions is a simple
expression.  For example, the following expression will display the
value of ‘pi’

     pi
          ⊣ pi = 3.1416

   This works well as long as it is acceptable to have the name of the
variable (or ‘ans’) printed along with the value.  To print the value of
a variable without printing its name, use the function ‘disp’.

   The ‘format’ command offers some control over the way Octave prints
values with ‘disp’ and through the normal echoing mechanism.

 -- : disp (X)
 -- : STR = disp (X)
     Display the value of X.

     For example:

          disp ("The value of pi is:"), disp (pi)

               ⊣ the value of pi is:
               ⊣ 3.1416

     Note that the output from ‘disp’ always ends with a newline.

     If an output value is requested, ‘disp’ prints nothing and returns
     the formatted output in a string.

     See also: *note fdisp: XREFfdisp.

 -- : list_in_columns (ARG, WIDTH, PREFIX)
     Return a string containing the elements of ARG listed in columns
     with an overall maximum width of WIDTH and optional prefix PREFIX.

     The argument ARG must be a cell array of character strings or a
     character array.

     If WIDTH is not specified or is an empty matrix, or less than or
     equal to zero, the width of the terminal screen is used.  Newline
     characters are used to break the lines in the output string.  For
     example:

          list_in_columns ({"abc", "def", "ghijkl", "mnop", "qrs", "tuv"}, 20)
               ⇒ abc     mnop
                  def     qrs
                  ghijkl  tuv

          whos ans
               ⇒
               Variables in the current scope:

                 Attr Name        Size                     Bytes  Class
                 ==== ====        ====                     =====  =====
                      ans         1x37                        37  char

               Total is 37 elements using 37 bytes

     See also: *note terminal_size: XREFterminal_size.

 -- : terminal_size ()
     Return a two-element row vector containing the current size of the
     terminal window in characters (rows and columns).

     See also: *note list_in_columns: XREFlist_in_columns.

 -- : format
 -- : format options
 -- : [FORMAT, FORMATSPACING] = format
     Reset or specify the format of the output produced by ‘disp’ and
     Octave’s normal echoing mechanism.

     This command only affects the display of numbers, but not how they
     are stored or computed.  To change the internal representation from
     the default double use one of the conversion functions such as
     ‘single’, ‘uint8’, ‘int64’, etc.

     By default, Octave displays 5 significant digits in a human
     readable form (option ‘short’ paired with ‘loose’ format for
     matrices).  If ‘format’ is invoked without any options, this
     default format is restored.

     Valid formats for floating point numbers are listed in the
     following table.

     ‘short’
          Fixed point format with 5 significant figures (default).

     ‘long’
          Fixed point format with 16 significant figures.

          As with the ‘short’ format, Octave will switch to an
          exponential ‘e’ format if it is unable to format a matrix
          properly using the current format.

     ‘short e’
     ‘long e’
          Exponential format.  The number to be represented is split
          between a mantissa and an exponent (power of 10).  The
          mantissa has 5 significant digits in the short format.  In the
          long format, double values are displayed with 16 significant
          digits and single values are displayed with 8.  For example,
          with the ‘short e’ format, ‘pi’ is displayed as ‘3.1416e+00’.

     ‘short E’
     ‘long E’
          Identical to ‘short e’ or ‘long e’ but displays an uppercase
          ‘E’ to indicate the exponent.  For example, with the ‘long E’
          format, ‘pi’ is displayed as ‘3.141592653589793E+00’.

     ‘short g’
     ‘long g’
          Optimally choose between fixed point and exponential format
          based on the magnitude of the number.  For example, with the
          ‘short g’ format, ‘pi .^ [2; 4; 8; 16; 32]’ is displayed as

               ans =

                     9.8696
                     97.409
                     9488.5
                 9.0032e+07
                 8.1058e+15

     ‘short eng’
     ‘long eng’
          Identical to ‘short e’ or ‘long e’ but displays the value
          using an engineering format, where the exponent is divisible
          by 3.  For example, with the ‘short eng’ format, ‘10 * pi’ is
          displayed as ‘31.416e+00’.

     ‘long G’
     ‘short G’
          Identical to ‘short g’ or ‘long g’ but displays an uppercase
          ‘E’ to indicate the exponent.

     ‘free’
     ‘none’
          Print output in free format, without trying to line up columns
          of matrices on the decimal point.  This is a raw format
          equivalent to the C++ code ‘std::cout << VARIABLE’.  In
          general, the result is a presentation with 6 significant
          digits where unnecessary precision (such as trailing zeros for
          integers) is suppressed.  Complex numbers are formatted as
          numeric pairs like this ‘(0.60419, 0.60709)’ instead of like
          this ‘0.60419 + 0.60709i’.

     The following formats affect all numeric output (floating point and
     integer types).

     "+"
     "+" "CHARS"
     ‘plus’
     ‘plus CHARS’
          Print a ‘+’ symbol for matrix elements greater than zero, a
          ‘-’ symbol for elements less than zero, and a space for zero
          matrix elements.  This format can be useful for examining the
          sparsity structure of a large matrix.  For very large matrices
          the function ‘spy’ which plots the sparsity pattern will be
          clearer.

          The optional argument CHARS specifies a list of 3 characters
          to use for printing values greater than zero, less than zero,
          and equal to zero.  For example, with the format "+" "+-.",
          the matrix ‘[1, 0, -1; -1, 0, 1]’ is displayed as

               ans =

               +.-
               -.+

     bank
          Print variable in a format appropriate for a currency (fixed
          format with two digits to the right of the decimal point).
          Only the real part of a variable is displayed, as the
          imaginary part makes no sense for a currency.

     native-hex
          Print the hexadecimal representation of numbers as they are
          stored in memory.  For example, on a workstation which stores
          8 byte real values in IEEE format with the least significant
          byte first, the value of ‘pi’ when printed in ‘native-hex’
          format is ‘400921fb54442d18’.

     hex
          The same as ‘native-hex’, but always print the most
          significant byte first.

     native-bit
          Print the bit representation of numbers as stored in memory.
          For example, the value of ‘pi’ is

               01000000000010010010000111111011
               01010100010001000010110100011000

          (shown here in two 32 bit sections for typesetting purposes)
          when printed in native-bit format on a workstation which
          stores 8 byte real values in IEEE format with the least
          significant byte first.

     bit
          The same as ‘native-bit’, but always print the most
          significant bits first.

     rat
          Print a rational approximation, i.e., values are approximated
          as the ratio of small integers.  For example, with the ‘rat’
          format, ‘pi’ is displayed as ‘355/113’.

     The following two options affect the display of all matrices.

     ‘compact’
          Remove blank lines around column number labels and between
          matrices producing more compact output with more data per
          page.

     ‘loose’
          Insert blank lines above and below column number labels and
          between matrices to produce a more readable output with less
          data per page.  (default).

     If called with one or two output arguments, and no inputs, return
     the current format and format spacing.

     See also: *note fixed_point_format: XREFfixed_point_format, *note
     output_precision: XREFoutput_precision, *note split_long_rows:
     XREFsplit_long_rows, *note print_empty_dimensions:
     XREFprint_empty_dimensions, *note rats: XREFrats.

* Menu:

* Paging Screen Output::


File: octave.info,  Node: Paging Screen Output,  Up: Terminal Output

14.1.1.1 Paging Screen Output
.............................

When running interactively, Octave normally sends all output directly to
the Command Window.  However, when using the CLI version of Octave this
can create a problem because large volumes of data will stream by before
you can read them.  In such cases, it is better to use a paging program
such as ‘less’ or ‘more’ which displays just one screenful at a time.
With ‘less’ (and some versions of ‘more’) you can also scan forward and
backward, and search for specific items.  The pager is enabled by the
command ‘more on’.

   Normally, no output is displayed by the pager until just before
Octave is ready to print the top level prompt, or read from the standard
input (for example, by using the ‘fscanf’ or ‘scanf’ functions).  This
means that there may be some delay before any output appears on your
screen if you have asked Octave to perform a significant amount of work
with a single command statement.  The function ‘fflush’ may be used to
force output to be sent to the pager (or any other stream) immediately.

   You can select the program to run as the pager with the ‘PAGER’
function, and configure the pager itself with the ‘PAGER_FLAGS’
function.

 -- : more
 -- : more on
 -- : more off
     Turn output pagination on or off.

     Without an argument, ‘more’ toggles the current state.

     The current state can be determined via ‘page_screen_output’.

     See also: *note page_screen_output: XREFpage_screen_output, *note
     page_output_immediately: XREFpage_output_immediately, *note PAGER:
     XREFPAGER, *note PAGER_FLAGS: XREFPAGER_FLAGS.

 -- : VAL = PAGER ()
 -- : OLD_VAL = PAGER (NEW_VAL)
 -- : PAGER (NEW_VAL, "local")
     Query or set the internal variable that specifies the program to
     use to display terminal output on your system.

     The default value is normally "less", "more", or "pg", depending on
     what programs are installed on your system.  *Note Installation::.

     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 PAGER_FLAGS: XREFPAGER_FLAGS, *note
     page_output_immediately: XREFpage_output_immediately, *note more:
     XREFmore, *note page_screen_output: XREFpage_screen_output.

 -- : VAL = PAGER_FLAGS ()
 -- : OLD_VAL = PAGER_FLAGS (NEW_VAL)
 -- : PAGER_FLAGS (NEW_VAL, "local")
     Query or set the internal variable that specifies the options to
     pass to the pager.

     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 PAGER: XREFPAGER, *note more: XREFmore, *note
     page_screen_output: XREFpage_screen_output, *note
     page_output_immediately: XREFpage_output_immediately.

 -- : VAL = page_screen_output ()
 -- : OLD_VAL = page_screen_output (NEW_VAL)
 -- : page_screen_output (NEW_VAL, "local")
     Query or set the internal variable that controls whether output
     intended for the terminal window that is longer than one page is
     sent through a pager.

     This allows you to view one screenful at a time.  Some pagers (such
     as ‘less’—see *note Installation::) are also capable of moving
     backward on the output.

     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 more: XREFmore, *note page_output_immediately:
     XREFpage_output_immediately, *note PAGER: XREFPAGER, *note
     PAGER_FLAGS: XREFPAGER_FLAGS.

 -- : VAL = page_output_immediately ()
 -- : OLD_VAL = page_output_immediately (NEW_VAL)
 -- : page_output_immediately (NEW_VAL, "local")
     Query or set the internal variable that controls whether Octave
     sends output to the pager as soon as it is available.

     Otherwise, Octave buffers its output and waits until just before
     the prompt is printed to flush it to the pager.

     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 page_screen_output: XREFpage_screen_output, *note
     more: XREFmore, *note PAGER: XREFPAGER, *note PAGER_FLAGS:
     XREFPAGER_FLAGS.

 -- : fflush (FID)
     Flush output to file descriptor FID.

     ‘fflush’ returns 0 on success and an OS dependent error value (−1
     on Unix) on error.

     Programming Note: Flushing is useful for ensuring that all pending
     output makes it to the screen before some other event occurs.  For
     example, it is always a good idea to flush the standard output
     stream before calling ‘input’.

     See also: *note fopen: XREFfopen, *note fclose: XREFfclose.


File: octave.info,  Node: Terminal Input,  Next: Simple File I/O,  Prev: Terminal Output,  Up: Basic Input and Output

14.1.2 Terminal Input
---------------------

Octave has three functions that make it easy to prompt users for input.
The ‘input’ and ‘menu’ functions are normally used for managing an
interactive dialog with a user, and the ‘keyboard’ function is normally
used for doing simple debugging.

 -- : ANS = input (PROMPT)
 -- : ANS = input (PROMPT, "s")
     Print PROMPT and wait for user input.

     For example,

          input ("Pick a number, any number! ")

     prints the prompt

          Pick a number, any number!

     and waits for the user to enter a value.  The string entered by the
     user is evaluated as an expression, so it may be a literal
     constant, a variable name, or any other valid Octave code.

     The number of return arguments, their size, and their class depend
     on the expression entered.

     If you are only interested in getting a literal string value, you
     can call ‘input’ with the character string "s" as the second
     argument.  This tells Octave to return the string entered by the
     user directly, without evaluating it first.

     Because there may be output waiting to be displayed by the pager,
     it is a good idea to always call ‘fflush (stdout)’ before calling
     ‘input’.  This will ensure that all pending output is written to
     the screen before your prompt.

     See also: *note yes_or_no: XREFyes_or_no, *note kbhit: XREFkbhit,
     *note pause: XREFpause, *note menu: XREFmenu, *note listdlg:
     XREFlistdlg.

 -- : CHOICE = menu (TITLE, OPT1, ...)
 -- : CHOICE = menu (TITLE, {OPT1, ...})
     Display a menu with heading TITLE and options OPT1, ..., and wait
     for user input.

     If the GUI is running, the menu is displayed graphically using
     ‘listdlg’.  Otherwise, the title and menu options are printed on
     the console.

     TITLE is a string and the options may be input as individual
     strings or as a cell array of strings.

     The return value CHOICE is the number of the option selected by the
     user counting from 1.  If the user aborts the dialog or makes an
     invalid selection then 0 is returned.

     This function is useful for interactive programs.  There is no
     limit to the number of options that may be passed in, but it may be
     confusing to present more than will fit easily on one screen.

     See also: *note input: XREFinput, *note listdlg: XREFlistdlg.

 -- : ANS = yes_or_no ("PROMPT")
     Ask the user a yes-or-no question.

     Return logical true if the answer is yes or false if the answer is
     no.

     Takes one argument, PROMPT, which is the string to display when
     asking the question.  PROMPT should end in a space; ‘yes-or-no’
     adds the string ‘(yes or no) ’ to it.  The user must confirm the
     answer with <RET> and can edit it until it has been confirmed.

     See also: *note input: XREFinput.

   For ‘input’, the normal command line history and editing functions
are available at the prompt.

   Octave also has a function that makes it possible to get a single
character from the keyboard without requiring the user to type a
carriage return.

 -- : kbhit ()
 -- : kbhit (1)
     Read a single keystroke from the keyboard.

     If called with an argument, don’t wait for a keypress.

     For example,

          x = kbhit ();

     will set X to the next character typed at the keyboard as soon as
     it is typed.

          x = kbhit (1);

     is identical to the above example, but doesn’t wait for a keypress,
     returning the empty string if no key is available.

     See also: *note input: XREFinput, *note pause: XREFpause.


File: octave.info,  Node: Simple File I/O,  Prev: Terminal Input,  Up: Basic Input and Output

14.1.3 Simple File I/O
----------------------

The ‘save’ and ‘load’ commands allow data to be written to and read from
disk files in various formats.  The default format of files written by
the ‘save’ command can be controlled using the functions
‘save_default_options’ and ‘save_precision’.

   As an example the following code creates a 3-by-3 matrix and saves it
to the file ‘myfile.mat’.

     A = [ 1:3; 4:6; 7:9 ];
     save myfile.mat A

   Once one or more variables have been saved to a file, they can be
read into memory using the ‘load’ command.

     load myfile.mat
     A
          ⊣ A =
          ⊣
          ⊣    1   2   3
          ⊣    4   5   6
          ⊣    7   8   9

 -- : save file
 -- : save options file
 -- : save options file V1 V2 ...
 -- : save options file -struct STRUCT
 -- : save options file -struct STRUCT F1 F2 ...
 -- : save - V1 V2 ...
 -- : STR = save ("-", "V1", "V2", ...)
     Save the named variables V1, V2, ..., in the file FILE.

     The special filename ‘-’ may be used to return the content of the
     variables as a string.  If no variable names are listed, Octave
     saves all the variables in the current scope.  Otherwise, full
     variable names or pattern syntax can be used to specify the
     variables to save.  If the ‘-struct’ modifier is used then the
     fields of the *scalar* struct are saved as if they were variables
     with the corresponding field names.  The ‘-struct’ option can be
     combined with specific field names F1, F2, ... to write only
     certain fields to the file.

     Valid options for the ‘save’ command are listed in the following
     table.  Options that modify the output format override the format
     specified by ‘save_default_options’.

     If save is invoked using the functional form

          save ("-option1", ..., "file", "v1", ...)

     then the OPTIONS, FILE, and variable name arguments (V1, ...) must
     be specified as character strings.

     If called with a filename of "-", write the output to stdout if
     nargout is 0, otherwise return the output in a character string.

     ‘-append’
          Append to the destination instead of overwriting.

     ‘-ascii’
          Save a matrix in a text file without a header or any other
          information.  The matrix must be 2-D and only the real part of
          any complex value is written to the file.  Numbers are stored
          in single-precision format and separated by spaces.
          Additional options for the ‘-ascii’ format are

          ‘-double’
               Store numbers in double-precision format.

          ‘-tabs’
               Separate numbers with tabs.

     ‘-binary’
          Save the data in Octave’s binary data format.

     ‘-float-binary’
          Save the data in Octave’s binary data format but using only
          single precision.  Use this format *only* if you know that all
          the values to be saved can be represented in single precision.

     ‘-hdf5’
          Save the data in HDF5 format.  (HDF5 is a free, portable,
          binary format developed by the National Center for
          Supercomputing Applications at the University of Illinois.)
          This format is only available if Octave was built with a link
          to the HDF5 libraries.

     ‘-float-hdf5’
          Save the data in HDF5 format but using only single precision.
          Use this format *only* if you know that all the values to be
          saved can be represented in single precision.

     ‘-V7’
     ‘-v7’
     ‘-7’
     ‘-mat7-binary’
          Save the data in MATLAB’s v7 binary data format.

     ‘-V6’
     ‘-v6’
     ‘-6’
     ‘-mat’
     ‘-mat-binary’
          Save the data in MATLAB’s v6 binary data format.

     ‘-V4’
     ‘-v4’
     ‘-4’
     ‘-mat4-binary’
          Save the data in the binary format written by MATLAB version
          4.

     ‘-text’
          Save the data in Octave’s text data format.  (default).

     ‘-zip’
     ‘-z’
          Use the gzip algorithm to compress the file.  This works on
          files that are compressed with gzip outside of Octave, and
          gzip can also be used to convert the files for backward
          compatibility.  This option is only available if Octave was
          built with a link to the zlib libraries.

     The list of variables to save may use wildcard patterns containing
     the following special characters:

     ‘?’
          Match any single character.

     ‘*’
          Match zero or more characters.

     ‘[ LIST ]’
          Match the list of characters specified by LIST.  If the first
          character is ‘!’ or ‘^’, match all characters except those
          specified by LIST.  For example, the pattern ‘[a-zA-Z]’ will
          match all lower and uppercase alphabetic characters.

          Wildcards may also be used in the field name specifications
          when using the ‘-struct’ modifier (but not in the struct name
          itself).

     Except when using the MATLAB binary data file format or the
     ‘-ascii’ format, saving global variables also saves the global
     status of the variable.  If the variable is restored at a later
     time using ‘load’, it will be restored as a global variable.

     The command

          save -binary data a b*

     saves the variable ‘a’ and all variables beginning with ‘b’ to the
     file ‘data’ in Octave’s binary format.

     See also: *note load: XREFload, *note save_default_options:
     XREFsave_default_options, *note save_header_format_string:
     XREFsave_header_format_string, *note save_precision:
     XREFsave_precision, *note dlmread: XREFdlmread, *note csvread:
     XREFcsvread, *note fread: XREFfread.

   There are three functions that modify the behavior of ‘save’.

 -- : VAL = save_default_options ()
 -- : OLD_VAL = save_default_options (NEW_VAL)
 -- : save_default_options (NEW_VAL, "local")
     Query or set the internal variable that specifies the default
     options for the ‘save’ command, and defines the default format.

     The default value is "-text" (Octave’s own text-based file format).
     See the documentation of the ‘save’ command for other choices.

     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 save: XREFsave, *note save_header_format_string:
     XREFsave_header_format_string, *note save_precision:
     XREFsave_precision.

 -- : VAL = save_precision ()
 -- : OLD_VAL = save_precision (NEW_VAL)
 -- : save_precision (NEW_VAL, "local")
     Query or set the internal variable that specifies the number of
     digits to keep when saving data in text format.

     The default value is 17 which is the minimum necessary for the
     lossless saving and restoring of IEEE-754 double values; For
     IEEE-754 single values the minimum value is 9.  If file size is a
     concern, it is probably better to choose a binary format for saving
     data rather than to reduce the precision of the saved values.

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

 -- : VAL = save_header_format_string ()
 -- : OLD_VAL = save_header_format_string (NEW_VAL)
 -- : save_header_format_string (NEW_VAL, "local")
     Query or set the internal variable that specifies the format string
     used for the comment line written at the beginning of text-format
     data files saved by Octave.

     The format string is passed to ‘strftime’ and must begin with the
     character ‘#’ and contain no newline characters.  If the value of
     ‘save_header_format_string’ is the empty string, the header comment
     is omitted from text-format data files.  The default value is

          "# Created by Octave VERSION, %a %b %d %H:%M:%S %Y %Z <USER@HOST>"

     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 strftime: XREFstrftime, *note save_default_options:
     XREFsave_default_options.

 -- : load file
 -- : load options file
 -- : load options file v1 v2 ...
 -- : S = load ("options", "file", "v1", "v2", ...)
 -- : load file options
 -- : load file options v1 v2 ...
 -- : S = load ("file", "options", "v1", "v2", ...)
     Load the named variables V1, V2, ..., from the file FILE.

     If no variables are specified then all variables found in the file
     will be loaded.  As with ‘save’, the list of variables to extract
     can be full names or use a pattern syntax.  The format of the file
     is automatically detected but may be overridden by supplying the
     appropriate option.

     If load is invoked using the functional form

          load ("-option1", ..., "file", "v1", ...)

     then the OPTIONS, FILE, and variable name arguments (V1, ...) must
     be specified as character strings.

     If a variable that is not marked as global is loaded from a file
     when a global symbol with the same name already exists, it is
     loaded in the global symbol table.  Also, if a variable is marked
     as global in a file and a local symbol exists, the local symbol is
     moved to the global symbol table and given the value from the file.

     If invoked with a single output argument, Octave returns data
     instead of inserting variables in the symbol table.  If the data
     file contains only numbers (TAB- or space-delimited columns), a
     matrix of values is returned.  Otherwise, ‘load’ returns a
     structure with members corresponding to the names of the variables
     in the file.

     The ‘load’ command can read data stored in Octave’s text and binary
     formats, and MATLAB’s binary format.  If compiled with zlib
     support, it can also load gzip-compressed files.  It will
     automatically detect the type of file and do conversion from
     different floating point formats (currently only IEEE big and
     little endian, though other formats may be added in the future).

     Valid options for ‘load’ are listed in the following table.

     ‘-force’
          This option is accepted for backward compatibility but is
          ignored.  Octave now overwrites variables currently in memory
          with those of the same name found in the file.

     ‘-ascii’
          Force Octave to assume the file contains columns of numbers in
          text format without any header or other information.  Data in
          the file will be loaded as a single numeric matrix with the
          name of the variable derived from the name of the file.

     ‘-binary’
          Force Octave to assume the file is in Octave’s binary format.

     ‘-hdf5’
          Force Octave to assume the file is in HDF5 format.  (HDF5 is a
          free, portable binary format developed by the National Center
          for Supercomputing Applications at the University of
          Illinois.)  Note that Octave can read HDF5 files not created
          by itself, but may skip some datasets in formats that it
          cannot support.  This format is only available if Octave was
          built with a link to the HDF5 libraries.

     ‘-import’
          This option is accepted for backward compatibility but is
          ignored.  Octave can now support multi-dimensional HDF data
          and automatically modifies variable names if they are invalid
          Octave identifiers.

     ‘-mat’
     ‘-mat-binary’
     ‘-6’
     ‘-v6’
     ‘-7’
     ‘-v7’
          Force Octave to assume the file is in MATLAB’s version 6 or 7
          binary format.

     ‘-mat4-binary’
     ‘-4’
     ‘-v4’
     ‘-V4’
          Force Octave to assume the file is in the binary format
          written by MATLAB version 4.

     ‘-text’
          Force Octave to assume the file is in Octave’s text format.

     See also: *note save: XREFsave, *note dlmwrite: XREFdlmwrite, *note
     csvwrite: XREFcsvwrite, *note fwrite: XREFfwrite.

 -- : STR = fileread (FILENAME)
     Read the contents of FILENAME and return it as a string.

     See also: *note fread: XREFfread, *note textread: XREFtextread,
     *note sscanf: XREFsscanf.

 -- : native_float_format ()
     Return the native floating point format as a string.

   It is possible to write data to a file in a similar way to the ‘disp’
function for writing data to the screen.  The ‘fdisp’ works just like
‘disp’ except its first argument is a file pointer as created by
‘fopen’.  As an example, the following code writes to data ‘myfile.txt’.

     fid = fopen ("myfile.txt", "w");
     fdisp (fid, "3/8 is ");
     fdisp (fid, 3/8);
     fclose (fid);

*Note Opening and Closing Files::, for details on how to use ‘fopen’ and
‘fclose’.

 -- : fdisp (FID, X)
     Display the value of X on the stream FID.

     For example:

          fdisp (stdout, "The value of pi is:"), fdisp (stdout, pi)

               ⊣ the value of pi is:
               ⊣ 3.1416

     Note that the output from ‘fdisp’ always ends with a newline.

     See also: *note disp: XREFdisp.

   Octave can also read and write matrices text files such as comma
separated lists.

 -- : dlmwrite (FILE, M)
 -- : dlmwrite (FILE, M, DELIM, R, C)
 -- : dlmwrite (FILE, M, KEY, VAL ...)
 -- : dlmwrite (FILE, M, "-append", ...)
 -- : dlmwrite (FID, ...)
     Write the numeric matrix M to the text file FILE using a delimiter.

     FILE should be a filename or a writable file ID given by ‘fopen’.

     The parameter DELIM specifies the delimiter to use to separate
     values on a row.  If no delimiter is specified the comma character
     ‘,’ is used.

     The value of R specifies the number of delimiter-only lines to add
     to the start of the file.

     The value of C specifies the number of delimiters to prepend to
     each line of data.

     If the argument "-append" is given, append to the end of FILE.

     In addition, the following keyword value pairs may appear at the
     end of the argument list:

     "append"
          Either "on" or "off".  See "-append" above.

     "delimiter"
          See DELIM above.

     "newline"
          The character(s) to separate each row.  Three special cases
          exist for this option.  "unix" is changed into "\n", "pc" is
          changed into "\r\n", and "mac" is changed into "\r".  Any
          other value is used directly as the newline separator.

     "roffset"
          See R above.

     "coffset"
          See C above.

     "precision"
          The precision to use when writing the file.  It can either be
          a format string (as used by fprintf) or a number of
          significant digits.

          dlmwrite ("file.csv", reshape (1:16, 4, 4));

          dlmwrite ("file.tex", a, "delimiter", "&", "newline", "\n")

     See also: *note dlmread: XREFdlmread, *note csvread: XREFcsvread,
     *note csvwrite: XREFcsvwrite.

 -- : DATA = dlmread (FILE)
 -- : DATA = dlmread (FILE, SEP)
 -- : DATA = dlmread (FILE, SEP, R0, C0)
 -- : DATA = dlmread (FILE, SEP, RANGE)
 -- : DATA = dlmread (..., "emptyvalue", EMPTYVAL)
     Read numeric data from the text file FILE which uses the delimiter
     SEP between data values.

     If SEP is not defined the separator between fields is determined
     from the file itself.

     The optional scalar arguments R0 and C0 define the starting row and
     column of the data to be read.  These values are indexed from zero,
     i.e., the first data row corresponds to an index of zero.

     The RANGE parameter specifies exactly which data elements are read.
     The first form of the parameter is a 4-element vector containing
     the upper left and lower right corners ‘[R0,C0,R1,C1]’ where the
     indices are zero-based.  Alternatively, a spreadsheet style form
     such as "A2..Q15" or "T1:AA5" can be used.  The lowest alphabetical
     index ’A’ refers to the first column.  The lowest row index is 1.

     FILE should be a filename or a file id given by ‘fopen’.  In the
     latter case, the file is read until end of file is reached.

     The "emptyvalue" option may be used to specify the value used to
     fill empty fields.  The default is zero.  Note that any non-numeric
     values, such as text, are also replaced by the "emptyvalue".

     See also: *note csvread: XREFcsvread, *note textscan: XREFtextscan,
     *note textread: XREFtextread, *note dlmwrite: XREFdlmwrite.

 -- : csvwrite (FILENAME, X)
 -- : csvwrite (FILENAME, X, DLM_OPT1, ...)
     Write the numeric matrix X to the file FILENAME in
     comma-separated-value (CSV) format.

     This function is equivalent to

          dlmwrite (FILENAME, X, ",", DLM_OPT1, ...)

     Any optional arguments are passed directly to ‘dlmwrite’ (*note
     dlmwrite: XREFdlmwrite.).

     See also: *note csvread: XREFcsvread, *note dlmwrite: XREFdlmwrite,
     *note dlmread: XREFdlmread.

 -- : X = csvread (FILENAME)
 -- : X = csvread (FILENAME, DLM_OPT1, ...)
     Read the comma-separated-value (CSV) file FILENAME into the matrix
     X.

     Note: only CSV files containing numeric data can be read.

     This function is equivalent to

          X = dlmread (FILENAME, "," , DLM_OPT1, ...)

     Any optional arguments are passed directly to ‘dlmread’ (*note
     dlmread: XREFdlmread.).

     See also: *note dlmread: XREFdlmread, *note textread: XREFtextread,
     *note textscan: XREFtextscan, *note csvwrite: XREFcsvwrite, *note
     dlmwrite: XREFdlmwrite.

   Formatted data from can be read from, or written to, text files as
well.

 -- : [A, ...] = textread (FILENAME)
 -- : [A, ...] = textread (FILENAME, FORMAT)
 -- : [A, ...] = textread (FILENAME, FORMAT, N)
 -- : [A, ...] = textread (FILENAME, FORMAT, PROP1, VALUE1, ...)
 -- : [A, ...] = textread (FILENAME, FORMAT, N, PROP1, VALUE1, ...)
     Read data from a text file.

     The file FILENAME is read and parsed according to FORMAT.  The
     function behaves like ‘strread’ except it works by parsing a file
     instead of a string.  See the documentation of ‘strread’ for
     details.

     In addition to the options supported by ‘strread’, this function
     supports two more:

        • "headerlines": The first VALUE number of lines of FILENAME are
          skipped.

        • "endofline": Specify a single character or "\r\n".  If no
          value is given, it will be inferred from the file.  If set to
          "" (empty string) EOLs are ignored as delimiters.

     The optional input N (format repeat count) specifies the number of
     times the format string is to be used or the number of lines to be
     read, whichever happens first while reading.  The former is
     equivalent to requesting that the data output vectors should be of
     length N.  Note that when reading files with format strings
     referring to multiple lines, N should rather be the number of lines
     to be read than the number of format string uses.

     If the format string is empty (not just omitted) and the file
     contains only numeric data (excluding headerlines), textread will
     return a rectangular matrix with the number of columns matching the
     number of numeric fields on the first data line of the file.  Empty
     fields are returned as zero values.

     Examples:

            Assume a data file like:
            1 a 2 b
            3 c 4 d
            5 e

            [a, b] = textread (f, "%f %s")
            returns two columns of data, one with doubles, the other a
            cellstr array:
            a = [1; 2; 3; 4; 5]
            b = {"a"; "b"; "c"; "d"; "e"}

            [a, b] = textread (f, "%f %s", 3)
            (read data into two culumns, try to use the format string
            three times)
            returns
            a = [1; 2; 3]
            b = {"a"; "b"; "c"}


            With a data file like:
            1
            a
            2
            b

            [a, b] = textread (f, "%f %s", 2)
            returns a = 1 and b = {"a"}; i.e., the format string is used
            only once because the format string refers to 2 lines of the
            data file.  To obtain 2x1 data output columns, specify N = 4
            (number of data lines containing all requested data) rather
            than 2.

     See also: *note strread: XREFstrread, *note load: XREFload, *note
     dlmread: XREFdlmread, *note fscanf: XREFfscanf, *note textscan:
     XREFtextscan.

 -- : C = textscan (FID, FORMAT)
 -- : C = textscan (FID, FORMAT, REPEAT)
 -- : C = textscan (FID, FORMAT, PARAM, VALUE, ...)
 -- : C = textscan (FID, FORMAT, REPEAT, PARAM, VALUE, ...)
 -- : C = textscan (STR, ...)
 -- : [C, POSITION, ERRMSG] = textscan (...)
     Read data from a text file or string.

     The string STR or file associated with FID is read from and parsed
     according to FORMAT.  The function is an extension of ‘strread’ and
     ‘textread’.  Differences include: the ability to read from either a
     file or a string, additional options, and additional format
     specifiers.

     The input is interpreted as a sequence of words, delimiters (such
     as whitespace), and literals.  The characters that form delimiters
     and whitespace are determined by the options.  The format consists
     of format specifiers interspersed between literals.  In the format,
     whitespace forms a delimiter between consecutive literals, but is
     otherwise ignored.

     The output C is a cell array where the number of columns is
     determined by the number of format specifiers.

     The first word of the input is matched to the first specifier of
     the format and placed in the first column of the output; the second
     is matched to the second specifier and placed in the second column
     and so forth.  If there are more words than specifiers then the
     process is repeated until all words have been processed or the
     limit imposed by REPEAT has been met (see below).

     The string FORMAT describes how the words in STR should be parsed.
     As in FSCANF, any (non-whitespace) text in the format that is not
     one of these specifiers is considered a literal.  If there is a
     literal between two format specifiers then that same literal must
     appear in the input stream between the matching words.

     The following specifiers are valid:

     ‘%f’
     ‘%f64’
     ‘%n’
          The word is parsed as a number and converted to double.

     ‘%f32’
          The word is parsed as a number and converted to single
          (float).

     ‘%d’
     ‘%d8’
     ‘%d16’
     ‘%d32’
     ‘%d64’
          The word is parsed as a number and converted to int8, int16,
          int32, or int64.  If no size is specified then int32 is used.

     ‘%u’
     ‘%u8’
     ‘%u16’
     ‘%u32’
     ‘%u64’
          The word is parsed as a number and converted to uint8, uint16,
          uint32, or uint64.  If no size is specified then uint32 is
          used.

     ‘%s’
          The word is parsed as a string ending at the last character
          before whitespace, an end-of-line, or a delimiter specified in
          the options.

     ‘%q’
          The word is parsed as a "quoted string".  If the first
          character of the string is a double quote (") then the string
          includes everything until a matching double quote—including
          whitespace, delimiters, and end-of-line characters.  If a pair
          of consecutive double quotes appears in the input, it is
          replaced in the output by a single double quote.  For
          examples, the input "He said ""Hello""" would return the value
          ’He said "Hello"’.

     ‘%c’
          The next character of the input is read.  This includes
          delimiters, whitespace, and end-of-line characters.

     ‘%[...]’
     ‘%[^...]’
          In the first form, the word consists of the longest run
          consisting of only characters between the brackets.  Ranges of
          characters can be specified by a hyphen; for example,
          %[0-9a-zA-Z] matches all alphanumeric characters (if the
          underlying character set is ASCII). Since MATLAB treats
          hyphens literally, this expansion only applies to alphanumeric
          characters.  To include ’-’ in the set, it should appear first
          or last in the brackets; to include ’]’, it should be the
          first character.  If the first character is ’^’ then the word
          consists of characters *not* listed.

     ‘%N...’
          For %s, %c %d, %f, %n, %u, an optional width can be specified
          as %Ns, etc.  where N is an integer > 1.  For %c, this causes
          exactly N characters to be read instead of a single character.
          For the other specifiers, it is an upper bound on the number
          of characters read; normal delimiters can cause fewer
          characters to be read.  For complex numbers, this limit
          applies to the real and imaginary components individually.
          For %f and %n, format specifiers like %N.Mf are allowed, where
          M is an upper bound on number of characters after the decimal
          point to be considered; subsequent digits are skipped.  For
          example, the specifier %8.2f would read 12.345e6 as 1.234e7.

     ‘%*...’
          The word specified by the remainder of the conversion
          specifier is skipped.

     ‘literals’
          In addition the format may contain literal character strings;
          these will be skipped during reading.  If the input string
          does not match this literal, the processing terminates.

     Parsed words corresponding to the first specifier are returned in
     the first output argument and likewise for the rest of the
     specifiers.

     By default, if there is only one input argument, FORMAT is "%f".
     This means that numbers are read from the input into a single
     column vector.  If FORMAT is explicitly empty ("") then textscan
     will return data in a number of columns matching the number of
     fields on the first data line of the input.  Either of these is
     suitable only when the input is exclusively numeric.

     For example, the string

          STR = "\
          Bunny Bugs   5.5\n\
          Duck Daffy  -7.5e-5\n\
          Penguin Tux   6"

     can be read using

          A = textscan (STR, "%s %s %f");

     The optional numeric argument REPEAT can be used for limiting the
     number of items read:

     -1
          Read all of the string or file until the end (default).

     N
          Read until the first of two conditions occurs: 1) the format
          has been processed N times, or 2) N lines of the input have
          been processed.  Zero (0) is an acceptable value for REPEAT.
          Currently, end-of-line characters inside %q, %c, and %[...]$
          conversions do not contribute to the line count.  This is
          incompatible with MATLAB and may change in future.

     The behavior of ‘textscan’ can be changed via property/value pairs.
     The following properties are recognized:

     "BufSize"
          This specifies the number of bytes to use for the internal
          buffer.  A modest speed improvement may be obtained by setting
          this to a large value when reading a large file, especially if
          the input contains long strings.  The default is 4096, or a
          value dependent on N if that is specified.

     "CollectOutput"
          A value of 1 or true instructs ‘textscan’ to concatenate
          consecutive columns of the same class in the output cell
          array.  A value of 0 or false (default) leaves output in
          distinct columns.

     "CommentStyle"
          Specify parts of the input which are considered comments and
          will be skipped.  VALUE is the comment style and can be either
          (1) A string or 1x1 cell string, to skip everything to the
          right of it; (2) A cell array of two strings, to skip
          everything between the first and second strings.  Comments are
          only parsed where whitespace is accepted and do not act as
          delimiters.

     "Delimiter"
          If VALUE is a string, any character in VALUE will be used to
          split the input into words.  If VALUE is a cell array of
          strings, any string in the array will be used to split the
          input into words.  (default value = any whitespace.)

     "EmptyValue"
          Value to return for empty numeric values in non-whitespace
          delimited data.  The default is NaN.  When the data type does
          not support NaN (int32 for example), then the default is zero.

     "EndOfLine"
          VALUE can be either an emtpy or one character specifying the
          end-of-line character, or the pair "\r\n" (CRLF). In the
          latter case, any of "\r", "\n" or "\r\n" is counted as a
          (single) newline.  If no value is given, "\r\n" is used.

     "HeaderLines"
          The first VALUE number of lines of FID are skipped.  Note that
          this does not refer to the first non-comment lines, but the
          first lines of any type.

     "MultipleDelimsAsOne"
          If VALUE is nonzero, treat a series of consecutive delimiters,
          without whitespace in between, as a single delimiter.
          Consecutive delimiter series need not be vertically aligned.
          Without this option, a single delimiter before the end of the
          line does not cause the line to be considered to end with an
          empty value, but a single delimiter at the start of a line
          causes the line to be considered to start with an empty value.

     "TreatAsEmpty"
          Treat single occurrences (surrounded by delimiters or
          whitespace) of the string(s) in VALUE as missing values.

     "ReturnOnError"
          If set to numerical 1 or true, return normally as soon as an
          error is encountered, such as trying to read a string using
          ‘%f’.  If set to 0 or false, return an error and no data.

     "Whitespace"
          Any character in VALUE will be interpreted as whitespace and
          trimmed; The default value for whitespace is " \b\r\n\t" (note
          the space).  Unless whitespace is set to "" (empty) AND at
          least one "%s" format conversion specifier is supplied, a
          space is always part of whitespace.

     When the number of words in STR or FID doesn’t match an exact
     multiple of the number of format conversion specifiers,
     ‘textscan’’s behavior depends on whether the last character of the
     string or file is an end-of-line as specified by the ‘EndOfLine’
     option:

     last character = end-of-line
          Data columns are padded with empty fields, NaN or 0 (for
          integer fields) so that all columns have equal length

     last character is not end-of-line
          Data columns are not padded; ‘textscan’ returns columns of
          unequal length

     The second output POSITION provides the location, in characters
     from the beginning of the file or string, where processing stopped.

     See also: *note dlmread: XREFdlmread, *note fscanf: XREFfscanf,
     *note load: XREFload, *note strread: XREFstrread, *note textread:
     XREFtextread.

   The ‘importdata’ function has the ability to work with a wide variety
of data.

 -- : A = importdata (FNAME)
 -- : A = importdata (FNAME, DELIMITER)
 -- : A = importdata (FNAME, DELIMITER, HEADER_ROWS)
 -- : [A, DELIMITER] = importdata (...)
 -- : [A, DELIMITER, HEADER_ROWS] = importdata (...)
     Import data from the file FNAME.

     Input parameters:

        • FNAME The name of the file containing data.

        • DELIMITER The character separating columns of data.  Use ‘\t’
          for tab.  (Only valid for ASCII files)

        • HEADER_ROWS The number of header rows before the data begins.
          (Only valid for ASCII files)

     Different file types are supported:

        • ASCII table

          Import ASCII table using the specified number of header rows
          and the specified delimiter.

        • Image file

        • MATLAB file

        • Spreadsheet files (depending on external software)

        • WAV file

     See also: *note textscan: XREFtextscan, *note dlmread: XREFdlmread,
     *note csvread: XREFcsvread, *note load: XREFload.

* Menu:

* Saving Data on Unexpected Exits::

