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

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

END-INFO-DIR-ENTRY

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

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

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

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


File: octave.info,  Node: 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 matrix or vector.

   Indices may be scalars, vectors, ranges, or the special operator ':',
which may be used to select entire rows or columns.

   Vectors are indexed using a single index expression.  Matrices (2-D)
and higher multi-dimensional arrays are indexed using either one index
or N indices where N is the dimension of the array.  When using a single
index expression to index 2-D or higher data the elements of the array
are taken in column-first order (like Fortran).

   The output from indexing assumes the dimensions of the index
expression.  For example:

     a(2)       # result is a scalar
     a(1:2)     # result is a row vector
     a([1; 2])  # result is a column vector

   As a special case, when a colon is used as a single index, the output
is a column vector containing all the elements of the vector or matrix.
For example:

     a(:)       # result is a column vector
     a(:)'      # result is a row vector

   The above two code idioms are often used in place of 'reshape' when a
simple vector, rather than an arbitrarily sized array, is needed.

   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

   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, 2, 3, 4];

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

An array with 'n' dimensions can be indexed using 'm' indices.  More
generally, the set of index tuples determining the result is formed by
the Cartesian product of the index vectors (or ranges or scalars).

   For the ordinary and most common case, 'm == n', and each index
corresponds to its respective dimension.  If 'm < n' and every index is
less than the size of the array in the i^{th} dimension, 'm(i) < n(i)',
then the index expression is padded with trailing singleton dimensions
('[ones (m-n, 1)]').  If 'm < n' but one of the indices 'm(i)' is
outside the size of the current array, then the last 'n-m+1' dimensions
are folded into a single dimension with an extent equal to the product
of extents of the original dimensions.  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

     a(2,1,2);   # Case (m == n): ans = 6
     a(2,1);     # Case (m < n), idx within array:
                 # equivalent to a(2,1,1), ans = 2
     a(2,4);     # Case (m < n), idx outside array:
                 # Dimension 2 & 3 folded into new dimension of size 2x2 = 4
                 # Select 2nd row, 4th element of [2, 4, 6, 8], ans = 8

   One advanced use of 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 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.

   The last example could also be written as

     13(ones (2, 3))

   It is more efficient to use indexing rather than the code
construction 'scalar * ones (N, M, ...)' 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 (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 a user unaware of these subtleties, is
to use the function 'repmat' for replicating smaller arrays into bigger
ones.

   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.

 -- Function File: IND = sub2ind (DIMS, I, J)
 -- Function File: IND = sub2ind (DIMS, S1, S2, ..., SN)
     Convert subscripts to a linear index.

     The following example shows how to convert the two-dimensional
     index '(2,3)' of a 3-by-3 matrix to a linear index.  The matrix is
     linearly indexed moving from one column to next, filling up all
     rows in each column.

          linear_index = sub2ind ([3, 3], 2, 3)
          => 8

     See also: *note ind2sub: XREFind2sub.

 -- Function File: [S1, S2, ..., SN] = ind2sub (DIMS, IND)
     Convert a linear index to subscripts.

     The following example shows how to convert the linear index '8' in
     a 3-by-3 matrix into a subscript.  The matrix is linearly indexed
     moving from one column to next, filling up all rows in each column.

          [r, c] = ind2sub ([3, 3], 8)
              => r =  2
              => c =  3

     See also: *note sub2ind: XREFsub2ind.

 -- Built-in Function: isindex (IND)
 -- Built-in Function: 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.

 -- Built-in Function: VAL = allow_noninteger_range_as_index ()
 -- Built-in Function: OLD_VAL = allow_noninteger_range_as_index
          (NEW_VAL)
 -- Built-in Function: allow_noninteger_range_as_index (NEW_VAL,
          "local")
     Query or set the internal variable that controls whether
     non-integer ranges are allowed as indices.  This might be useful
     for MATLAB compatibility; however, it is still not entirely
     compatible because MATLAB treats the range expression differently
     in different contexts.

     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: 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, and is allowed to be a list of variable names or index
expressions.  See also *note Index Expressions::, and *note Assignment
Ops::.

* Menu:

* Call by Value::
* Recursion::


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

 -- Built-in Function: VAL = max_recursion_depth ()
 -- Built-in Function: OLD_VAL = max_recursion_depth (NEW_VAL)
 -- Built-in Function: 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.

   ---------- 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: 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, or they must be broadcastable to the same
     shape.

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.

 -- Built-in Function: ctranspose (X)
     Return the complex conjugate transpose of X.  This function and x'
     are equivalent.

     See also: *note transpose: XREFtranspose.

 -- Built-in Function: 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.

 -- Built-in Function: minus (X, Y)
     This function and x - y are equivalent.

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

 -- Built-in Function: 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.

 -- Built-in Function: 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.

 -- Built-in Function: 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.

 -- Built-in Function: mtimes (X, Y)
 -- Built-in Function: 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.

 -- Built-in Function: plus (X, Y)
 -- Built-in Function: 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.

 -- Built-in Function: power (X, Y)
     Return the element-by-element operation of X raised to the Y power.
     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.

     This function and x .^ y are equivalent.

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

 -- Built-in Function: 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.

 -- Built-in Function: times (X, Y)
 -- Built-in Function: 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.

 -- Built-in Function: transpose (X)
     Return the transpose of X.  This function and x.'  are equivalent.

     See also: *note ctranspose: XREFctranspose.

 -- Built-in Function: uminus (X)
     This function and - x are equivalent.

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

 -- Built-in Function: 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::.

 -- Built-in Function: 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.

 -- Built-in Function: 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.

 -- Built-in Function: 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.

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

     See also: *note isequaln: XREFisequaln.

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

 -- Built-in Function: 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.

 -- Built-in Function: 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.

 -- Built-in Function: 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.

 -- Built-in Function: and (X, Y)
 -- Built-in Function: and (X1, X2, ...)
     Return the logical AND of X and Y.  This function is equivalent to
     'x & y'.  If more 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.

 -- Built-in Function: not (X)
     Return the logical NOT of X.  This function is equivalent to '! x'.

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

 -- Built-in Function: or (X, Y)
 -- Built-in Function: or (X1, X2, ...)
     Return the logical OR of X and Y.  This function is equivalent to
     'x | y'.  If more 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 (BOOLEAN1(:))'.
     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 (BOOLEAN1(:))'.
     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.  The Octave parser may be instructed to behave in the same
manner, but its use is strongly discouraged.

 -- Built-in Function: VAL = do_braindead_shortcircuit_evaluation ()
 -- Built-in Function: OLD_VAL = do_braindead_shortcircuit_evaluation
          (NEW_VAL)
 -- Built-in Function: do_braindead_shortcircuit_evaluation (NEW_VAL,
          "local")
     Query or set the internal variable that controls whether Octave
     will do short-circuit evaluation of '|' and '&' operators inside
     the conditions of if or while statements.

     This feature is only provided for compatibility with MATLAB and
     should not be used unless you are porting old code that relies on
     this feature.

     To obtain short-circuit behavior for logical expressions in new
     programs, you should always use the '&&' and '||' operators.

     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.

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

 -- Built-in Function: merge (MASK, TVAL, FVAL)
 -- Built-in Function: 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 '/'.  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.

 -- Built-in Function: eval (TRY)
 -- Built-in Function: eval (TRY, CATCH)
     Parse the string TRY and evaluate it as if it were an Octave
     program.  If that 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.

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

 -- Built-in 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

 -- Command: run SCRIPT
 -- Function File: 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 file name 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 directory to the directory where SCRIPT is
     found.  'run' then executes the script, and returns to the original
     directory.

     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.

 -- Built-in Function: evalin (CONTEXT, TRY)
 -- Built-in Function: 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.

 -- Built-in Function: 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
non-zero, 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
non-zero.

   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 non-zero, 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 non-zero.

   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 non-zero, 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 non-zero.

   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.

   The KEY variable may also be omitted.  If it is, the brackets are
also optional.  This is useful for cycling through the values of all the
structure elements when the names of the elements do not need to be
known.


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.

 -- Built-in Function: nargin ()
 -- Built-in Function: nargin (FCN)
     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 built-in functions.

     See also: *note nargout: XREFnargout, *note varargin: XREFvarargin,
     *note isargout: XREFisargout, *note varargout: XREFvarargout, *note
     nthargout: XREFnthargout.

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

 -- Built-in Function: VAL = silent_functions ()
 -- Built-in Function: OLD_VAL = silent_functions (NEW_VAL)
 -- Built-in Function: 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::.

 -- Function File: nthargout (N, FUNC, ...)
 -- Function File: nthargout (N, NTOT, FUNC, ...)
     Return the Nth output argument of function given by the function
     handle or string FUNC.  Any arguments after FUNC are passed 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.

 -- Built-in Function: nargout ()
 -- Built-in Function: nargout (FCN)
     Within a function, return the number of values the caller expects
     to receive.  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")

     will return 2, because 'histc' has two outputs, whereas

          nargout (@imread)

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

     At the top level, 'nargout' with no argument is undefined and will
     produce an error.  'nargout' does not work for built-in functions
     and returns -1 for all anonymous functions.

     See also: *note nargin: XREFnargin, *note varargin: XREFvarargin,
     *note isargout: XREFisargout, *note varargout: XREFvarargout, *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, 'nargchk', 'narginchk' and
'nargoutchk' are available which provide similar error checking.

 -- Function File: MSGSTR = nargchk (MINARGS, MAXARGS, NARGS)
 -- Function File: MSGSTR = nargchk (MINARGS, MAXARGS, NARGS, "string")
 -- Function File: MSGSTRUCT = nargchk (MINARGS, MAXARGS, NARGS,
          "struct")
     Return an appropriate error message string (or structure) if the
     number of inputs requested is invalid.

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

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

 -- Function File: narginchk (MINARGS, MAXARGS)
     Check for correct number of arguments or 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 need to 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 nargchk: XREFnargchk, *note nargoutchk:
     XREFnargoutchk, *note error: XREFerror, *note nargout: XREFnargout,
     *note nargin: XREFnargin.

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

     On the first form, returns an error unless the number of arguments
     in its caller is between the values of MINARGS and MAXARGS.  It
     does nothing otherwise.  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 need to be a numeric scalar.  Zero, Inf
     and negative are all valid, and they can have the same value.

     For backward compatibility reasons, 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 see that the number of output
     arguments supplied to a function is within an acceptable range.

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


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

 -- Function File: [REG, PROP] = parseparams (PARAMS)
 -- Function File: [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.


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

 -- Built-in Function: 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 nargin: XREFnargin,
     *note varargin: XREFvarargin, *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.

 -- Function File: [R1, R2, ..., RN] = deal (A)
 -- Function File: [R1, R2, ..., RN] = deal (A1, A2, ..., AN)

     Copy the input parameters into the corresponding output parameters.
     If only one 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;


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.

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

 -- Command: edit NAME
 -- Command: edit FIELD VALUE
 -- Command: VALUE = edit get FIELD
     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 Function 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'.

 -- Built-in Function: mfilename ()
 -- Built-in Function: mfilename ("fullpath")
 -- Built-in Function: 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 file
     name, but not the extension.  Given the argument "fullpathext",
     include the directory part of the file name and the extension.

 -- Built-in Function: VAL = ignore_function_time_stamp ()
 -- Built-in Function: 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.

 -- Built-in Function: addpath (DIR1, ...)
 -- Built-in Function: 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")

     See also: *note path: XREFpath, *note rmpath: XREFrmpath, *note
     genpath: XREFgenpath, *note pathdef: XREFpathdef, *note savepath:
     XREFsavepath, *note pathsep: XREFpathsep.

 -- Built-in Function: genpath (DIR)
 -- Built-in Function: genpath (DIR, SKIP, ...)
     Return a path constructed from DIR and all its subdirectories.  If
     additional string parameters are given, the resulting path will
     exclude directories with those names.

 -- Built-in Function: 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")

     See also: *note path: XREFpath, *note addpath: XREFaddpath, *note
     genpath: XREFgenpath, *note pathdef: XREFpathdef, *note savepath:
     XREFsavepath, *note pathsep: XREFpathsep.

 -- Function File: savepath ()
 -- Function File: savepath (FILE)
 -- Function 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, '~/.octaverc' is used.  If successful, 'savepath' returns
     0.

     See also: *note path: XREFpath, *note addpath: XREFaddpath, *note
     rmpath: XREFrmpath, *note genpath: XREFgenpath, *note pathdef:
     XREFpathdef.

 -- Built-in Function: path (...)
     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.

 -- Function File: VAL = pathdef ()
     Return the default path for Octave.  The path information is
     extracted from one of three sources.  The possible sources, in
     order of preference, are:

       1. '~/.octaverc'

       2. '<octave-home>/.../<version>/m/startup/octaverc'

       3. Octave's path prior to changes by any octaverc.

     See also: *note path: XREFpath, *note addpath: XREFaddpath, *note
     rmpath: XREFrmpath, *note genpath: XREFgenpath, *note savepath:
     XREFsavepath.

 -- Built-in Function: VAL = pathsep ()
 -- Built-in Function: OLD_VAL = pathsep (NEW_VAL)
     Query or set the character used to separate directories in a path.

     See also: *note filesep: XREFfilesep.

 -- Built-in Function: rehash ()
     Reinitialize Octave's load path directory cache.

 -- Built-in Function: file_in_loadpath (FILE)
 -- Built-in Function: 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.

     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
     find_dir_in_path: XREFfind_dir_in_path, *note path: XREFpath.

 -- Built-in Function: 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.

 -- Built-in Function: 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.

 -- Built-in Function: find_dir_in_path (DIR)
 -- Built-in Function: find_dir_in_path (DIR, "all")
     Return the full name of the path element matching DIR.  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".

     The second argument is optional.  If it 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'.


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 ()
         ## Call 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.

 -- Built-in Function: [...] = 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.

 -- Built-in Function: AUTOLOAD_MAP = autoload ()
 -- Built-in Function: autoload (FUNCTION, FILE)
 -- Built-in Function: autoload (..., "remove")
     Define FUNCTION to autoload from FILE.

     The second argument, FILE, should be an absolute file name 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.

 -- Built-in 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.

 -- Built-in Function: munlock ()
 -- Built-in Function: 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.

 -- Built-in Function: mislocked ()
 -- Built-in Function: 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 constuctors 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.

 -- Built-in Function: source (FILE)
     Parse and execute the contents of FILE.

     This is equivalent to executing commands from a script file, but
     without requiring the file to be named 'FILE.m'.

     See also: *note run: XREFrun.


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

 -- Built-in Function: 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.

 -- Built-in Function: S = functions (FCN_HANDLE)
     Return a structure containing information about the function handle
     FCN_HANDLE.

     The structure S always contains these 3 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.
     It's behavior may change in the future and programs should not
     depend on a particular output.

 -- Built-in Function: 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.

 -- Built-in Function: str2func (FCN_NAME)
 -- Built-in Function: 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.


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.


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

 -- Built-in Function: inline (STR)
 -- Built-in Function: inline (STR, ARG1, ...)
 -- Built-in Function: 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
     inbuilt 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.

 -- Built-in Function: 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.

 -- Built-in Function: formula (FUN)
     Return a character string representing the inline function FUN.
     Note that 'char (FUN)' is equivalent to 'formula (FUN)'.

     See also: *note argnames: XREFargnames, *note inline: XREFinline,
     *note vectorize: XREFvectorize.

 -- Function File: symvar (S)
     Identify the argument names in the function defined by a string.
     Common constant names such as 'pi', 'NaN', 'Inf', 'eps', 'i' or 'j'
     are ignored.  The arguments that are found are returned in a cell
     array of strings.  If no variables are found then the returned cell
     array is empty.


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.

'audio'
     Functions for playing and recording sounds.

'deprecated'
     Out-of-date functions which will eventually be removed from Octave.

'elfun'
     Elementary functions, principally trigonometric.

'@ftp'
     Class functions for the FTP object.

'general'
     Miscellaneous matrix manipulations, like 'flipud', 'rot90', and
     'triu', as well as other basic functions, like 'ismatrix',
     'nargchk', etc.

'geometry'
     Functions related to Delaunay triangulation.

'help'
     Functions for Octave's built-in help system.

'image'
     Image processing tools.  These functions require the X Window
     System.

'io'
     Input-output functions.

'linear-algebra'
     Functions for linear algebra.

'miscellaneous'
     Functions that don't really belong anywhere else.

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

 -- Built-in Function: error (TEMPLATE, ...)
 -- Built-in Function: error (ID, TEMPLATE, ...)
     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 more
     commands.  This is useful for aborting from functions or scripts.

     If the error message does not end with a new line 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 locate the exact location of the error:

          f ()
          error: nargin != 1
          error: called from:
          error:   error at line -1, column -1
          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 new line 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 new line 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 (e.g., "\n" => newline) are processed in TEMPLATE
     regardless of whether TEMPLATE has been defined within single
     quotes as long as there are two or more input arguments.  Use a
     second backslash to stop interpolation of the escape 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 {Function File} 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:
     -|
     -|   -- Function File: 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 http://www.octave.org and via the help@octave.org
     -|  mailing list.

 -- Function File: print_usage ()
 -- Function File: print_usage (NAME)
     Print the usage message for a function.  When called with no input
     arguments the 'print_usage' function displays the usage message of
     the currently executing function.

     See also: *note help: XREFhelp.

 -- Built-in Function: usage (MSG)
     Print the message MSG, prefixed by the string 'usage: ', and set
     Octave's internal error state such that control will return to the
     top level without evaluating any more commands.  This is useful for
     aborting from functions.

     After 'usage' is evaluated, Octave will print a traceback of all
     the function calls leading to the usage message.

     You should use this function for reporting problems errors that
     result from an improper call to a function, such as calling a
     function with an incorrect number of arguments, or with arguments
     of the wrong type.  For example, most functions distributed with
     Octave begin with code like this

          if (nargin != 2)
            usage ("foo (a, b)");
          endif

     to check for the proper number of arguments.

 -- Function File: beep ()
     Produce a beep from the speaker (or visual bell).

     See also: *note puts: XREFputs, *note fputs: XREFfputs, *note
     printf: XREFprintf, *note fprintf: XREFfprintf.

 -- Built-in Function: VAL = beep_on_error ()
 -- Built-in Function: OLD_VAL = beep_on_error (NEW_VAL)
 -- Built-in Function: 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

 -- Built-in Function: LASTERR = lasterror ()
 -- Built-in Function: lasterror (ERR)
 -- Built-in Function: 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.

 -- Built-in Function: [MSG, MSGID] = lasterr ()
 -- Built-in Function: lasterr (MSG)
 -- Built-in Function: 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.

   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
shown in the next example.  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.

   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, non-existent 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

 -- Built-in Function: 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.

 -- Built-in Function: ERR = errno ()
 -- Built-in Function: ERR = errno (VAL)
 -- Built-in Function: ERR = errno (NAME)
     Return the current value of the system-dependent variable errno,
     set its value to VAL and return the previous value, or return the
     named error code given NAME as a character string, or -1 if NAME is
     not found.

 -- Built-in Function: errno_list ()
     Return a structure containing the system-dependent errno values.


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

 -- Built-in Function: 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.

 -- Built-in Function: warning (TEMPLATE, ...)
 -- Built-in Function: warning (ID, TEMPLATE, ...)
 -- Built-in Function: warning ("on", ID)
 -- Built-in Function: warning ("off", ID)
 -- Built-in Function: warning ("query", ID)
 -- Built-in Function: warning ("error", ID)
 -- Built-in Function: warning (STATE, ID, "local")
     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 '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.

     The optional message identifier allows users to enable or disable
     warnings tagged by ID.  A message identifier is of the form
     "NAMESPACE:WARNING-NAME". Octave's own warnings use the "Octave"
     namespace (*note XREFwarning_ids::).  The special identifier "all"
     may be used to set the state of all warnings.

     If the first argument is "on" or "off", set the state of a
     particular warning using the identifier ID.  If the first argument
     is "query", query the state of this warning instead.  If the
     identifier is omitted, a value of "all" is assumed.  If you set the
     state of a warning to "error", the warning named by ID is handled
     as if it were an error instead.  So, for example, the following
     handles all warnings as errors:

          warning ("error");

     If the state is "on", "off", or "error" and the third argument is
     "local", 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.

     Implementation Note: For compatibility with MATLAB, escape
     sequences (e.g., "\n" => newline) are processed in TEMPLATE
     regardless of whether TEMPLATE has been defined within single
     quotes as long as there are two or more input arguments.  Use a
     second backslash to stop interpolation of the escape sequence
     (e.g., "\\n") or use the 'regexptranslate' function.

     See also: *note warning_ids: XREFwarning_ids, *note lastwarn:
     XREFlastwarn, *note error: XREFerror.

 -- Built-in Function: [MSG, MSGID] = lastwarn ()
 -- Built-in Function: lastwarn (MSG)
 -- Built-in Function: 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: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:broadcast'
     Warn when performing broadcasting operations.  By default, this is
     enabled.  See *note Broadcasting:: in the chapter Vectorization and
     Faster Code Execution of the manual.

'Octave:built-in-variable-assignment'
     By default, the 'Octave:built-in-variable-assignment' 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: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:fopen-file-in-path'
     By default, the 'Octave:fopen-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:load-file-in-path'
     By default, the 'Octave:load-file-in-path' warning is enabled.

'Octave:logical-conversion'
     By default, the 'Octave:logical-conversion' warning is enabled.

'Octave:matlab-incompatible'
     Print warnings for Octave language features that may cause
     compatibility problems with MATLAB.  By default, the
     'Octave:matlab-incompatible' warning is disabled.  The -traditional
     or -braindead startup options for Octave may also be of use, *note
     Command Line Options::.

'Octave:md5sum-file-in-path'
     By default, the 'Octave:md5sum-file-in-path' 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: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 MATLAB always short circuits if
     any logical operators are used in a condition.  You can turn on the
     option

          do_braindead_shortcircuit_evaluation (1)

     if you would like to enable this short-circuit evaluation in
     Octave.  Note that the '&&' and '||' operators always short circuit
     in both Octave and MATLAB, so it's only necessary to enable
     MATLAB-style short-circuiting if it's too arduous to modify
     existing code that relies on this behavior.  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:singular-matrix-div'
     By default, the 'Octave:singular-matrix-div' warning is enabled.

'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:undefined-return-values'
     If the 'Octave:undefined-return-values' warning is disabled, print
     a warning if a function does not define all the values in the
     return list which are expected.  By default, the
     'Octave:undefined-return-values' warning is enabled.

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

 -- Built-in Function: VAL = debug_on_interrupt ()
 -- Built-in Function: OLD_VAL = debug_on_interrupt (NEW_VAL)
 -- Built-in Function: 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.

 -- Built-in Function: VAL = debug_on_warning ()
 -- Built-in Function: OLD_VAL = debug_on_warning (NEW_VAL)
 -- Built-in Function: 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.

 -- Built-in Function: VAL = debug_on_error ()
 -- Built-in Function: OLD_VAL = debug_on_error (NEW_VAL)
 -- Built-in Function: 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.

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

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

 -- Built-in Function: RLINE = dbstop ("FUNC")
 -- Built-in Function: RLINE = dbstop ("FUNC", LINE)
 -- Built-in Function: RLINE = dbstop ("FUNC", LINE1, LINE2, ...)
     Set a breakpoint in function FUNC.

     Arguments are

     FUNC
          Function name as a string variable.  When already in debug
          mode this should be left out and only the line should be
          given.

     LINE
          Line number where the breakpoint should be set.  Multiple
          lines may be given as separate arguments or as a vector.

     When called with a single argument FUNC, the breakpoint is set at
     the first executable line in the named function.

     The optional output RLINE is the real line number where the
     breakpoint was set.  This can differ from 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.

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

 -- Built-in Function: dbstatus ()
 -- Built-in Function: BRK_LIST = dbstatus ()
 -- Built-in Function: BRK_LIST = dbstatus ("FUNC")
     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.

     The optional return argument BRK_LIST is a struct array with the
     following fields.

     name
          The name of the function with a breakpoint.

     file
          The name of the m-file where the function code is located.

     line
          A line number, or vector of line numbers, with a breakpoint.

     See also: *note dbclear: XREFdbclear, *note dbwhere: XREFdbwhere.

Reusing the previous example, 'dbstatus ("asind")' will return 29.  The
breakpoints listed can then be cleared with the 'dbclear' function.

 -- Built-in Function: dbclear ("FUNC")
 -- Built-in Function: dbclear ("FUNC", LINE, ...)
 -- Built-in Function: dbclear (LINE, ...)
     Delete a breakpoint in the function FUNC.

     Arguments are

     FUNC
          Function name as a string variable.  When already in debug
          mode this argument should be omitted and only the line number
          should be given.

     LINE
          Line number from which to remove a breakpoint.  Multiple lines
          may be given as separate arguments or as a vector.

     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.

     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", filemarker(), "func2"])
     => 5

   Note that 'filemarker' returns the character that marks subfunctions
from the file containing them.  Unless the default has been changed this
character is '>'.  Thus, a quicker and more normal way to set the
breakpoint would be

     dbstop func1>func2

   Another simple way of setting a breakpoint in an Octave script is the
use of the 'keyboard' function.

 -- Built-in Function: keyboard ()
 -- Built-in Function: keyboard ("PROMPT")
     This function is normally used for simple debugging.  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 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.

 -- Command: dbwhere
     In debugging mode, report the current file and line number where
     execution is stopped.

     See also: *note dbstatus: XREFdbstatus, *note dbcont: XREFdbcont,
     *note dbstep: XREFdbstep, *note dbup: XREFdbup.

 -- Command: dbtype
 -- Command: dbtype LINENO
 -- Command: dbtype STARTL:ENDL
 -- Command: dbtype STARTL:END
 -- Command: dbtype FUNC
 -- Command: dbtype FUNC LINENO
 -- Command: dbtype FUNC STARTL:ENDL
 -- Command: 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 dbwhere: XREFdbwhere, *note dbstatus: XREFdbstatus,
     *note dbstop: XREFdbstop.

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

   You may also use 'isdebugmode' to determine whether the debugger is
currently active.

 -- Built-in Function: 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'.

 -- Command: dbstep
 -- Command: dbstep N
 -- Command: dbstep in
 -- Command: dbstep out
 -- Command: 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.

 -- Command: dbstack
 -- Command: dbstack N
 -- Command: dbstack -COMPLETENAMES
 -- Built-in Function: [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 file names.  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 dbstatus: XREFdbstatus.

 -- Built-in Function: dbup
 -- Built-in Function: 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.

 -- Built-in Function: dbdown
 -- Built-in Function: 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.

 -- Command: profile on
 -- Command: profile off
 -- Command: profile resume
 -- Command: profile clear
 -- Function File: S = profile ("status")
 -- Function File: 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 calls like 'S = profile ("info")'.

     'profile clear'
          Clear all collected profiler data.

     'profile resume'
          Restart profiling without cleaning up the old data and instead
          all newly collected statistics are added to the already
          existing ones.

     'S = profile ("status")'
          Return a structure filled with certain 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.  Furthermore, 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.

 -- Function File: profshow (DATA)
 -- Function File: profshow (DATA, N)
     Show flat profiler results.

     This command prints out profiler data as a flat profile.  DATA is
     the structure returned by 'profile ("info")'.  If N is given, it
     specifies the number of functions to show in the profile; functions
     are sorted in descending order by total time spent in them.  If
     there are more than N included in the profile, those will not be
     shown.  N defaults to 20.

     The attribute column shows 'R' for recursive functions and nothing
     otherwise.

     See also: *note profexplore: XREFprofexplore, *note profile:
     XREFprofile.

 -- Function File: profexplore ()
 -- Function File: 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.

 -- Built-in Function: 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.

 -- Built-in Function: 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.

 -- Built-in Function: 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.

 -- Command: format
 -- Command: format options
     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 in a field that
          is a maximum of 10 characters wide.  (default).

          If Octave is unable to format a matrix so that columns line up
          on the decimal point and all numbers fit within the maximum
          field width then it switches to an exponential 'e' format.

     'long'
          Fixed point format with 15 significant figures in a field that
          is a maximum of 20 characters wide.

          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 and 15
          digits in the long format.  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.14159265358979E+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.4159e+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 also causes complex
          numbers to be 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 nonzero matrix elements and a space for
          zero matrix elements.  This format can be very useful for
          examining the structure of a large sparse matrix.

          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,
          '[1, 0, -1; -1, 0, 1]' is displayed as

               ans =

               +.-
               -.+

     'bank'
          Print in a fixed format with two digits to the right of the
          decimal point.

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

     See also: *note fixed_point_format: XREFfixed_point_format, *note
     output_max_field_width: XREFoutput_max_field_width, *note
     output_precision: XREFoutput_precision, *note split_long_rows:
     XREFsplit_long_rows, *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 any output intended
for your terminal that is more than one screen long to a paging program,
such as 'less' or 'more'.  This avoids the problem of having a large
volume of output stream by before you can read it.  With 'less' (and
some versions of 'more') you can also scan forward and backward, and
search for specific items.

   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 using the 'PAGER'
function, and you can turn paging off by using the function 'more'.

 -- Command: more
 -- Command: more on
 -- Command: 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.

 -- Built-in Function: VAL = PAGER ()
 -- Built-in Function: OLD_VAL = PAGER (NEW_VAL)
 -- Built-in Function: 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.

 -- Built-in Function: VAL = PAGER_FLAGS ()
 -- Built-in Function: OLD_VAL = PAGER_FLAGS (NEW_VAL)
 -- Built-in Function: 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.

 -- Built-in Function: VAL = page_screen_output ()
 -- Built-in Function: OLD_VAL = page_screen_output (NEW_VAL)
 -- Built-in Function: 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.

 -- Built-in Function: VAL = page_output_immediately ()
 -- Built-in Function: OLD_VAL = page_output_immediately (NEW_VAL)
 -- Built-in Function: 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.

 -- Built-in Function: fflush (FID)
     Flush output to FID.  This 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'.

     'fflush' returns 0 on success and an OS dependent error value (-1
     on Unix) on error.

     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.

 -- Built-in Function: ANS = input (PROMPT)
 -- Built-in Function: ANS = input (PROMPT, "s")
     Print a 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 expression.

     Currently, 'input' only returns one value, regardless of the number
     of values produced by the evaluation of the expression.

     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.

 -- Function File: menu (TITLE, OPT1, ...)
     Print a title string followed by a series of options.  Each option
     will be printed along with a number.  The return value is the
     number of the option selected by the user.  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 disp: XREFdisp, *note printf: XREFprintf, *note
     input: XREFinput.

 -- Built-in Function: 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.

 -- Built-in Function: kbhit ()
 -- Built-in Function: 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.


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

 -- Command: save file
 -- Command: save options file
 -- Command: save options file V1 V2 ...
 -- Command: save options file -struct STRUCT F1 F2 ...
     Save the named variables V1, V2, ..., in the file FILE.  The
     special filename '-' may be used to write output to the terminal.
     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, fields F1 F2 ... of the scalar
     structure STRUCT are saved as if they were variables with
     corresponding names.  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.

     '-append'
          Append to the destination instead of overwriting.

     '-ascii'
          Save a single matrix in a text file without header or any
          other information.

     '-binary'
          Save the data in Octave's binary data format.

     '-float-binary'
          Save the data in Octave's binary data format but only using
          single precision.  Only use this format 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 only using single precision.
          Only use this format 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
          equally on files that are compressed with gzip outside of
          octave, and gzip can equally 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 dlmread: XREFdlmread, *note
     csvread: XREFcsvread, *note fread: XREFfread.

   There are three functions that modify the behavior of 'save'.

 -- Built-in Function: VAL = save_default_options ()
 -- Built-in Function: OLD_VAL = save_default_options (NEW_VAL)
 -- Built-in Function: 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.
     Typical values include "-ascii", "-text -zip".  The default value
     is '-text'.

     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.

 -- Built-in Function: VAL = save_precision ()
 -- Built-in Function: OLD_VAL = save_precision (NEW_VAL)
 -- Built-in Function: 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.

     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.

 -- Built-in Function: VAL = save_header_format_string ()
 -- Built-in Function: OLD_VAL = save_header_format_string (NEW_VAL)
 -- Built-in Function: 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 should 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: XREFsave.

 -- Command: load file
 -- Command: load options file
 -- Command: load options file v1 v2 ...
 -- Command: S = load ("options", "file", "v1", "v2", ...)
 -- Command: load file options
 -- Command: load file options v1 v2 ...
 -- Command: 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.

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

 -- Built-in Function: 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'.

 -- Built-in Function: 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.

 -- Function File: dlmwrite (FILE, M)
 -- Function File: dlmwrite (FILE, M, DELIM, R, C)
 -- Function File: dlmwrite (FILE, M, KEY, VAL ...)
 -- Function File: dlmwrite (FILE, M, "-append", ...)
 -- Function File: dlmwrite (FID, ...)
     Write the matrix M to the named file using delimiters.

     FILE should be a file name or writable file ID given by 'fopen'.

     The parameter DELIM specifies the delimiter to use to separate
     values on a row.

     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 use 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".
          Other values for this option are kept as is.

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

 -- Built-in Function: DATA = dlmread (FILE)
 -- Built-in Function: DATA = dlmread (FILE, SEP)
 -- Built-in Function: DATA = dlmread (FILE, SEP, R0, C0)
 -- Built-in Function: DATA = dlmread (FILE, SEP, RANGE)
 -- Built-in Function: DATA = dlmread (..., "emptyvalue", EMPTYVAL)
     Read the matrix DATA from a text file.  If not defined the
     separator between fields is determined from the file itself.
     Otherwise the separation character is defined by SEP.

     Given two scalar arguments R0 and C0, these define the starting row
     and column of the data to be read.  These values are indexed from
     zero, such that the first row corresponds to an index of zero.

     The RANGE parameter may be a 4-element vector containing the upper
     left and lower right corner '[R0,C0,R1,C1]' where the lowest index
     value is zero.  Alternatively, a spreadsheet style range 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 file name or 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.

     See also: *note csvread: XREFcsvread, *note textscan: XREFtextscan,
     *note textread: XREFtextread, *note dlmwrite: XREFdlmwrite.

 -- Function File: csvwrite (FILENAME, X)
 -- Function File: csvwrite (FILENAME, X, DLM_OPTS)
     Write the matrix X to the file FILENAME in comma-separated-value
     format.

     This function is equivalent to

          dlmwrite (FILENAME, X, ",", ...)

     See also: *note csvread: XREFcsvread, *note dlmwrite: XREFdlmwrite,
     *note dlmread: XREFdlmread.

 -- Function File: X = csvread (FILENAME)
 -- Function File: X = csvread (FILENAME, DLM_OPTS)
     Read the comma-separated-value file FILENAME into the matrix X.

     This function is equivalent to

          X = dlmread (FILENAME, "," , ...)

     See also: *note csvwrite: XREFcsvwrite, *note dlmread: XREFdlmread,
     *note dlmwrite: XREFdlmwrite.

   Formatted data from can be read from, or written to, text files as
well.

 -- Function File: [A, ...] = textread (FILENAME)
 -- Function File: [A, ...] = textread (FILENAME, FORMAT)
 -- Function File: [A, ...] = textread (FILENAME, FORMAT, N)
 -- Function File: [A, ...] = textread (FILENAME, FORMAT, PROP1, VALUE1,
          ...)
 -- Function File: [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 specifies the number of data lines to read; in
     this sense it differs slightly from the format repeat count in
     strread.

     If the format string is empty (not: 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.

     See also: *note strread: XREFstrread, *note load: XREFload, *note
     dlmread: XREFdlmread, *note fscanf: XREFfscanf, *note textscan:
     XREFtextscan.

 -- Function File: C = textscan (FID, FORMAT)
 -- Function File: C = textscan (FID, FORMAT, N)
 -- Function File: C = textscan (FID, FORMAT, PARAM, VALUE, ...)
 -- Function File: C = textscan (FID, FORMAT, N, PARAM, VALUE, ...)
 -- Function File: C = textscan (STR, ...)
 -- Function File: [C, POSITION] = textscan (FID, ...)
     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 behaves like 'strread' except it
     can also read from file instead of a string.  See the documentation
     of 'strread' for details.

     In addition to the options supported by 'strread', this function
     supports a few more:

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

        * "endofline": Specify "\r", "\n" or "\r\n" (for CR, LF, or
          CRLF). If no value is given, it will be inferred from the
          file.  If set to "" (empty string) EOLs are ignored as
          delimiters and added to whitespace.

        * "headerlines": The first VALUE number of lines of FID are
          skipped.

        * "returnonerror": If set to numerical 1 or true (default),
          return normally when read errors have been encountered.  If
          set to 0 or false, return an error and no data.  As the string
          or file is read by columns rather than by rows, and because
          textscan is fairly forgiving as regards read errors, setting
          this option may have little or no actual effect.

     When reading from a character string, optional input argument N
     specifies the number of times FORMAT should be used (i.e., to limit
     the amount of data read).  When reading from file, N specifies the
     number of data lines to read; in this sense it differs slightly
     from the format repeat count in strread.

     The output C is a cell array whose second dimension is determined
     by the number of format specifiers.

     The second output, POSITION, provides the position, in characters,
     from the beginning of the file.

     If the format string is empty (not: omitted) and the file contains
     only numeric data (excluding headerlines), textscan will return
     data in a number of columns matching the number of numeric fields
     on the first data line of the file.

     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.

 -- Function File: A = importdata (FNAME)
 -- Function File: A = importdata (FNAME, DELIMITER)
 -- Function File: A = importdata (FNAME, DELIMITER, HEADER_ROWS)
 -- Function File: [A, DELIMITER] = importdata (...)
 -- Function File: [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::


File: octave.info,  Node: Saving Data on Unexpected Exits,  Up: Simple File I/O

14.1.3.1 Saving Data on Unexpected Exits
........................................

If Octave for some reason exits unexpectedly it will by default save the
variables available in the workspace to a file in the current directory.
By default this file is named 'octave-workspace' and can be loaded into
memory with the 'load' command.  While the default behavior most often
is reasonable it can be changed through the following functions.

 -- Built-in Function: VAL = crash_dumps_octave_core ()
 -- Built-in Function: OLD_VAL = crash_dumps_octave_core (NEW_VAL)
 -- Built-in Function: crash_dumps_octave_core (NEW_VAL, "local")
     Query or set the internal variable that controls whether Octave
     tries to save all current variables to the file 'octave-workspace'
     if it crashes or receives a hangup, terminate or similar signal.

     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 octave_core_file_limit: XREFoctave_core_file_limit,
     *note octave_core_file_name: XREFoctave_core_file_name, *note
     octave_core_file_options: XREFoctave_core_file_options.

 -- Built-in Function: VAL = sighup_dumps_octave_core ()
 -- Built-in Function: OLD_VAL = sighup_dumps_octave_core (NEW_VAL)
 -- Built-in Function: sighup_dumps_octave_core (NEW_VAL, "local")
     Query or set the internal variable that controls whether Octave
     tries to save all current variables to the file 'octave-workspace'
     if it receives a hangup signal.

     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.

 -- Built-in Function: VAL = sigterm_dumps_octave_core ()
 -- Built-in Function: OLD_VAL = sigterm_dumps_octave_core (NEW_VAL)
 -- Built-in Function: sigterm_dumps_octave_core (NEW_VAL, "local")
     Query or set the internal variable that controls whether Octave
     tries to save all current variables to the file 'octave-workspace'
     if it receives a terminate signal.

     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.

 -- Built-in Function: VAL = octave_core_file_options ()
 -- Built-in Function: OLD_VAL = octave_core_file_options (NEW_VAL)
 -- Built-in Function: octave_core_file_options (NEW_VAL, "local")
     Query or set the internal variable that specifies the options used
     for saving the workspace data if Octave aborts.  The value of
     'octave_core_file_options' should follow the same format as the
     options for the 'save' function.  The default value is Octave's
     binary format.

     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 crash_dumps_octave_core:
     XREFcrash_dumps_octave_core, *note octave_core_file_name:
     XREFoctave_core_file_name, *note octave_core_file_limit:
     XREFoctave_core_file_limit.

 -- Built-in Function: VAL = octave_core_file_limit ()
 -- Built-in Function: OLD_VAL = octave_core_file_limit (NEW_VAL)
 -- Built-in Function: octave_core_file_limit (NEW_VAL, "local")
     Query or set the internal variable that specifies the maximum
     amount of memory (in kilobytes) of the top-level workspace that
     Octave will attempt to save when writing data to the crash dump
     file (the name of the file is specified by OCTAVE_CORE_FILE_NAME).
     If OCTAVE_CORE_FILE_OPTIONS flags specify a binary format, then
     OCTAVE_CORE_FILE_LIMIT will be approximately the maximum size of
     the file.  If a text file format is used, then the file could be
     much larger than the limit.  The default value is -1 (unlimited)

     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 crash_dumps_octave_core:
     XREFcrash_dumps_octave_core, *note octave_core_file_name:
     XREFoctave_core_file_name, *note octave_core_file_options:
     XREFoctave_core_file_options.

 -- Built-in Function: VAL = octave_core_file_name ()
 -- Built-in Function: OLD_VAL = octave_core_file_name (NEW_VAL)
 -- Built-in Function: octave_core_file_name (NEW_VAL, "local")
     Query or set the internal variable that specifies the name of the
     file used for saving data from the top-level workspace if Octave
     aborts.  The default value is "octave-workspace"

     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 crash_dumps_octave_core:
     XREFcrash_dumps_octave_core, *note octave_core_file_name:
     XREFoctave_core_file_name, *note octave_core_file_options:
     XREFoctave_core_file_options.


File: octave.info,  Node: C-Style I/O Functions,  Prev: Basic Input and Output,  Up: Input and Output

14.2 C-Style I/O Functions
==========================

Octave's C-style input and output functions provide most of the
functionality of the C programming language's standard I/O library.  The
argument lists for some of the input functions are slightly different,
however, because Octave has no way of passing arguments by reference.

   In the following, FILE refers to a file name and 'fid' refers to an
integer file number, as returned by 'fopen'.

   There are three files that are always available.  Although these
files can be accessed using their corresponding numeric file ids, you
should always use the symbolic names given in the table below, since it
will make your programs easier to understand.

 -- Built-in Function: stdin ()
     Return the numeric value corresponding to the standard input
     stream.  When Octave is used interactively, this is filtered
     through the command line editing functions.

     See also: *note stdout: XREFstdout, *note stderr: XREFstderr.

 -- Built-in Function: stdout ()
     Return the numeric value corresponding to the standard output
     stream.  Data written to the standard output is normally filtered
     through the pager.

     See also: *note stdin: XREFstdin, *note stderr: XREFstderr.

 -- Built-in Function: stderr ()
     Return the numeric value corresponding to the standard error
     stream.  Even if paging is turned on, the standard error is not
     sent to the pager.  It is useful for error messages and prompts.

     See also: *note stdin: XREFstdin, *note stdout: XREFstdout.

* Menu:

* Opening and Closing Files::
* Simple Output::
* Line-Oriented Input::
* Formatted Output::
* Output Conversion for Matrices::
* Output Conversion Syntax::
* Table of Output Conversions::
* Integer Conversions::
* Floating-Point Conversions::
* Other Output Conversions::
* Formatted Input::
* Input Conversion Syntax::
* Table of Input Conversions::
* Numeric Input Conversions::
* String Input Conversions::
* Binary I/O::
* Temporary Files::
* EOF and Errors::
* File Positioning::


File: octave.info,  Node: Opening and Closing Files,  Next: Simple Output,  Up: C-Style I/O Functions

14.2.1 Opening and Closing Files
--------------------------------

When reading data from a file it must be opened for reading first, and
likewise when writing to a file.  The 'fopen' function returns a pointer
to an open file that is ready to be read or written.  Once all data has
been read from or written to the opened file it should be closed.  The
'fclose' function does this.  The following code illustrates the basic
pattern for writing to a file, but a very similar pattern is used when
reading a file.

     filename = "myfile.txt";
     fid = fopen (filename, "w");
     # Do the actual I/O here...
     fclose (fid);

 -- Built-in Function: [FID, MSG] = fopen (NAME, MODE, ARCH)
 -- Built-in Function: FID_LIST = fopen ("all")
 -- Built-in Function: [FILE, MODE, ARCH] = fopen (FID)
     The first form of the 'fopen' function opens the named file with
     the specified mode (read-write, read-only, etc.)  and architecture
     interpretation (IEEE big endian, IEEE little endian, etc.), and
     returns an integer value that may be used to refer to the file
     later.  If an error occurs, FID is set to -1 and MSG contains the
     corresponding system error message.  The MODE is a one or two
     character string that specifies whether the file is to be opened
     for reading, writing, or both.

     The second form of the 'fopen' function returns a vector of file
     ids corresponding to all the currently open files, excluding the
     'stdin', 'stdout', and 'stderr' streams.

     The third form of the 'fopen' function returns information about
     the open file given its file id.

     For example,

          myfile = fopen ("splat.dat", "r", "ieee-le");

     opens the file 'splat.dat' for reading.  If necessary, binary
     numeric values will be read assuming they are stored in IEEE format
     with the least significant bit first, and then converted to the
     native representation.

     Opening a file that is already open simply opens it again and
     returns a separate file id.  It is not an error to open a file
     several times, though writing to the same file through several
     different file ids may produce unexpected results.

     The possible values 'mode' may have are

     'r'
          Open a file for reading.

     'w'
          Open a file for writing.  The previous contents are discarded.

     'a'
          Open or create a file for writing at the end of the file.

     'r+'
          Open an existing file for reading and writing.

     'w+'
          Open a file for reading or writing.  The previous contents are
          discarded.

     'a+'
          Open or create a file for reading or writing at the end of the
          file.

     Append a "t" to the mode string to open the file in text mode or a
     "b" to open in binary mode.  On Windows and Macintosh systems, text
     mode reading and writing automatically converts linefeeds to the
     appropriate line end character for the system (carriage-return
     linefeed on Windows, carriage-return on Macintosh).  The default if
     no mode is specified is binary mode.

     Additionally, you may append a "z" to the mode string to open a
     gzipped file for reading or writing.  For this to be successful,
     you must also open the file in binary mode.

     The parameter ARCH is a string specifying the default data format
     for the file.  Valid values for ARCH are:

     'native'
          The format of the current machine (this is the default).

     'ieee-be'
          IEEE big endian format.

     'ieee-le'
          IEEE little endian format.

     however, conversions are currently only supported for 'native'
     'ieee-be', and 'ieee-le' formats.

     See also: *note fclose: XREFfclose, *note fgets: XREFfgets, *note
     fgetl: XREFfgetl, *note fscanf: XREFfscanf, *note fread: XREFfread,
     *note fputs: XREFfputs, *note fdisp: XREFfdisp, *note fprintf:
     XREFfprintf, *note fwrite: XREFfwrite, *note fskipl: XREFfskipl,
     *note fseek: XREFfseek, *note frewind: XREFfrewind, *note ftell:
     XREFftell, *note feof: XREFfeof, *note ferror: XREFferror, *note
     fclear: XREFfclear, *note fflush: XREFfflush, *note freport:
     XREFfreport.

 -- Built-in Function: fclose (FID)
 -- Built-in Function: fclose ("all")
     Close the specified file.  If successful, 'fclose' returns 0,
     otherwise, it returns -1.  The second form of the 'fclose' call
     closes all open files except 'stdout', 'stderr', and 'stdin'.

     See also: *note fopen: XREFfopen, *note freport: XREFfreport.

 -- Function File: is_valid_file_id (FID)
     Return true if FID refers to an open file.

     See also: *note fopen: XREFfopen.


File: octave.info,  Node: Simple Output,  Next: Line-Oriented Input,  Prev: Opening and Closing Files,  Up: C-Style I/O Functions

14.2.2 Simple Output
--------------------

Once a file has been opened for writing a string can be written to the
file using the 'fputs' function.  The following example shows how to
write the string 'Free Software is needed for Free Science' to the file
'free.txt'.

     filename = "free.txt";
     fid = fopen (filename, "w");
     fputs (fid, "Free Software is needed for Free Science");
     fclose (fid);

 -- Built-in Function: fputs (FID, STRING)
     Write a string to a file with no formatting.

     Return a non-negative number on success and EOF on error.

     See also: *note fdisp: XREFfdisp, *note fprintf: XREFfprintf, *note
     fwrite: XREFfwrite, *note fopen: XREFfopen.

   A function much similar to 'fputs' is available for writing data to
the screen.  The 'puts' function works just like 'fputs' except it
doesn't take a file pointer as its input.

 -- Built-in Function: puts (STRING)
     Write a string to the standard output with no formatting.

     Return a non-negative number on success and EOF on error.

     See also: *note fputs: XREFfputs, *note disp: XREFdisp.


File: octave.info,  Node: Line-Oriented Input,  Next: Formatted Output,  Prev: Simple Output,  Up: C-Style I/O Functions

14.2.3 Line-Oriented Input
--------------------------

To read from a file it must be opened for reading using 'fopen'.  Then a
line can be read from the file using 'fgetl' as the following code
illustrates

     fid = fopen ("free.txt");
     txt = fgetl (fid)
          -| Free Software is needed for Free Science
     fclose (fid);

This of course assumes that the file 'free.txt' exists and contains the
line 'Free Software is needed for Free Science'.

 -- Built-in Function: STR = fgetl (FID)
 -- Built-in Function: STR = fgetl (FID, LEN)
     Read characters from a file, stopping after a newline, or EOF, or
     LEN characters have been read.  The characters read, excluding the
     possible trailing newline, are returned as a string.

     If LEN is omitted, 'fgetl' reads until the next newline character.

     If there are no more characters to read, 'fgetl' returns -1.

     To read a line and return the terminating newline see 'fgets'.

     See also: *note fgets: XREFfgets, *note fscanf: XREFfscanf, *note
     fread: XREFfread, *note fopen: XREFfopen.

 -- Built-in Function: STR = fgets (FID)
 -- Built-in Function: STR = fgets (FID, LEN)
     Read characters from a file, stopping after a newline, or EOF, or
     LEN characters have been read.  The characters read, including the
     possible trailing newline, are returned as a string.

     If LEN is omitted, 'fgets' reads until the next newline character.

     If there are no more characters to read, 'fgets' returns -1.

     To read a line and discard the terminating newline see 'fgetl'.

     See also: *note fputs: XREFfputs, *note fgetl: XREFfgetl, *note
     fscanf: XREFfscanf, *note fread: XREFfread, *note fopen: XREFfopen.

 -- Built-in Function: NLINES = fskipl (FID)
 -- Built-in Function: NLINES = fskipl (FID, COUNT)
 -- Built-in Function: NLINES = fskipl (FID, Inf)
     Read and skip COUNT lines from the file descriptor FID.  'fskipl'
     discards characters until an end-of-line is encountered exactly
     COUNT-times, or until the end-of-file marker is found.

     If COUNT is omitted, it defaults to 1.  COUNT may also be 'Inf', in
     which case lines are skipped until the end of the file.  This form
     is suitable for counting the number of lines in a file.

     Returns the number of lines skipped (end-of-line sequences
     encountered).

     See also: *note fgetl: XREFfgetl, *note fgets: XREFfgets, *note
     fscanf: XREFfscanf, *note fopen: XREFfopen.


File: octave.info,  Node: Formatted Output,  Next: Output Conversion for Matrices,  Prev: Line-Oriented Input,  Up: C-Style I/O Functions

14.2.4 Formatted Output
-----------------------

This section describes how to call 'printf' and related functions.

   The following functions are available for formatted output.  They are
modeled after the C language functions of the same name, but they
interpret the format template differently in order to improve the
performance of printing vector and matrix values.

 -- Built-in Function: printf (TEMPLATE, ...)
     Print optional arguments under the control of the template string
     TEMPLATE to the stream 'stdout' and return the number of characters
     printed.

     See the Formatted Output section of the GNU Octave manual for a
     complete description of the syntax of the template string.

     See also: *note fprintf: XREFfprintf, *note sprintf: XREFsprintf,
     *note scanf: XREFscanf.

 -- Built-in Function: fprintf (FID, TEMPLATE, ...)
     This function is just like 'printf', except that the output is
     written to the stream FID instead of 'stdout'.  If FID is omitted,
     the output is written to 'stdout'.

     See also: *note fputs: XREFfputs, *note fdisp: XREFfdisp, *note
     fwrite: XREFfwrite, *note fscanf: XREFfscanf, *note printf:
     XREFprintf, *note sprintf: XREFsprintf, *note fopen: XREFfopen.

 -- Built-in Function: sprintf (TEMPLATE, ...)
     This is like 'printf', except that the output is returned as a
     string.  Unlike the C library function, which requires you to
     provide a suitably sized string as an argument, Octave's 'sprintf'
     function returns the string, automatically sized to hold all of the
     items converted.

     See also: *note printf: XREFprintf, *note fprintf: XREFfprintf,
     *note sscanf: XREFsscanf.

   The 'printf' function can be used to print any number of arguments.
The template string argument you supply in a call provides information
not only about the number of additional arguments, but also about their
types and what style should be used for printing them.

   Ordinary characters in the template string are simply written to the
output stream as-is, while "conversion specifications" introduced by a
'%' character in the template cause subsequent arguments to be formatted
and written to the output stream.  For example,

     pct = 37;
     filename = "foo.txt";
     printf ("Processed %d%% of '%s'.\nPlease be patient.\n",
             pct, filename);

produces output like

     Processed 37% of 'foo.txt'.
     Please be patient.

   This example shows the use of the '%d' conversion to specify that a
scalar argument should be printed in decimal notation, the '%s'
conversion to specify printing of a string argument, and the '%%'
conversion to print a literal '%' character.

   There are also conversions for printing an integer argument as an
unsigned value in octal, decimal, or hexadecimal radix ('%o', '%u', or
'%x', respectively); or as a character value ('%c').

   Floating-point numbers can be printed in normal, fixed-point notation
using the '%f' conversion or in exponential notation using the '%e'
conversion.  The '%g' conversion uses either '%e' or '%f' format,
depending on what is more appropriate for the magnitude of the
particular number.

   You can control formatting more precisely by writing "modifiers"
between the '%' and the character that indicates which conversion to
apply.  These slightly alter the ordinary behavior of the conversion.
For example, most conversion specifications permit you to specify a
minimum field width and a flag indicating whether you want the result
left- or right-justified within the field.

   The specific flags and modifiers that are permitted and their
interpretation vary depending on the particular conversion.  They're all
described in more detail in the following sections.


File: octave.info,  Node: Output Conversion for Matrices,  Next: Output Conversion Syntax,  Prev: Formatted Output,  Up: C-Style I/O Functions

14.2.5 Output Conversion for Matrices
-------------------------------------

When given a matrix value, Octave's formatted output functions cycle
through the format template until all the values in the matrix have been
printed.  For example:

     printf ("%4.2f %10.2e %8.4g\n", hilb (3));

          -| 1.00   5.00e-01   0.3333
          -| 0.50   3.33e-01     0.25
          -| 0.33   2.50e-01      0.2

   If more than one value is to be printed in a single call, the output
functions do not return to the beginning of the format template when
moving on from one value to the next.  This can lead to confusing output
if the number of elements in the matrices are not exact multiples of the
number of conversions in the format template.  For example:

     printf ("%4.2f %10.2e %8.4g\n", [1, 2], [3, 4]);

          -| 1.00   2.00e+00        3
          -| 4.00

   If this is not what you want, use a series of calls instead of just
one.


File: octave.info,  Node: Output Conversion Syntax,  Next: Table of Output Conversions,  Prev: Output Conversion for Matrices,  Up: C-Style I/O Functions

14.2.6 Output Conversion Syntax
-------------------------------

This section provides details about the precise syntax of conversion
specifications that can appear in a 'printf' template string.

   Characters in the template string that are not part of a conversion
specification are printed as-is to the output stream.

   The conversion specifications in a 'printf' template string have the
general form:

     % FLAGS WIDTH [ . PRECISION ] TYPE CONVERSION

   For example, in the conversion specifier '%-10.8ld', the '-' is a
flag, '10' specifies the field width, the precision is '8', the letter
'l' is a type modifier, and 'd' specifies the conversion style.  (This
particular type specifier says to print a numeric argument in decimal
notation, with a minimum of 8 digits left-justified in a field at least
10 characters wide.)

   In more detail, output conversion specifications consist of an
initial '%' character followed in sequence by:

   * Zero or more "flag characters" that modify the normal behavior of
     the conversion specification.

   * An optional decimal integer specifying the "minimum field width".
     If the normal conversion produces fewer characters than this, the
     field is padded with spaces to the specified width.  This is a
     _minimum_ value; if the normal conversion produces more characters
     than this, the field is _not_ truncated.  Normally, the output is
     right-justified within the field.

     You can also specify a field width of '*'.  This means that the
     next argument in the argument list (before the actual value to be
     printed) is used as the field width.  The value is rounded to the
     nearest integer.  If the value is negative, this means to set the
     '-' flag (see below) and to use the absolute value as the field
     width.

   * An optional "precision" to specify the number of digits to be
     written for the numeric conversions.  If the precision is
     specified, it consists of a period ('.') followed optionally by a
     decimal integer (which defaults to zero if omitted).

     You can also specify a precision of '*'.  This means that the next
     argument in the argument list (before the actual value to be
     printed) is used as the precision.  The value must be an integer,
     and is ignored if it is negative.

   * An optional "type modifier character".  This character is ignored
     by Octave's 'printf' function, but is recognized to provide
     compatibility with the C language 'printf'.

   * A character that specifies the conversion to be applied.

   The exact options that are permitted and how they are interpreted
vary between the different conversion specifiers.  See the descriptions
of the individual conversions for information about the particular
options that they use.


File: octave.info,  Node: Table of Output Conversions,  Next: Integer Conversions,  Prev: Output Conversion Syntax,  Up: C-Style I/O Functions

14.2.7 Table of Output Conversions
----------------------------------

Here is a table summarizing what all the different conversions do:

'%d', '%i'
     Print an integer as a signed decimal number.  *Note Integer
     Conversions::, for details.  '%d' and '%i' are synonymous for
     output, but are different when used with 'scanf' for input (*note
     Table of Input Conversions::).

'%o'
     Print an integer as an unsigned octal number.  *Note Integer
     Conversions::, for details.

'%u'
     Print an integer as an unsigned decimal number.  *Note Integer
     Conversions::, for details.

'%x', '%X'
     Print an integer as an unsigned hexadecimal number.  '%x' uses
     lowercase letters and '%X' uses uppercase.  *Note Integer
     Conversions::, for details.

'%f'
     Print a floating-point number in normal (fixed-point) notation.
     *Note Floating-Point Conversions::, for details.

'%e', '%E'
     Print a floating-point number in exponential notation.  '%e' uses
     lowercase letters and '%E' uses uppercase.  *Note Floating-Point
     Conversions::, for details.

'%g', '%G'
     Print a floating-point number in either normal (fixed-point) or
     exponential notation, whichever is more appropriate for its
     magnitude.  '%g' uses lowercase letters and '%G' uses uppercase.
     *Note Floating-Point Conversions::, for details.

'%c'
     Print a single character.  *Note Other Output Conversions::.

'%s'
     Print a string.  *Note Other Output Conversions::.

'%%'
     Print a literal '%' character.  *Note Other Output Conversions::.

   If the syntax of a conversion specification is invalid, unpredictable
things will happen, so don't do this.  If there aren't enough function
arguments provided to supply values for all the conversion
specifications in the template string, or if the arguments are not of
the correct types, the results are unpredictable.  If you supply more
arguments than conversion specifications, the extra argument values are
simply ignored; this is sometimes useful.


File: octave.info,  Node: Integer Conversions,  Next: Floating-Point Conversions,  Prev: Table of Output Conversions,  Up: C-Style I/O Functions

14.2.8 Integer Conversions
--------------------------

This section describes the options for the '%d', '%i', '%o', '%u', '%x',
and '%X' conversion specifications.  These conversions print integers in
various formats.

   The '%d' and '%i' conversion specifications both print an numeric
argument as a signed decimal number; while '%o', '%u', and '%x' print
the argument as an unsigned octal, decimal, or hexadecimal number
(respectively).  The '%X' conversion specification is just like '%x'
except that it uses the characters 'ABCDEF' as digits instead of
'abcdef'.

   The following flags are meaningful:

'-'
     Left-justify the result in the field (instead of the normal
     right-justification).

'+'
     For the signed '%d' and '%i' conversions, print a plus sign if the
     value is positive.

' '
     For the signed '%d' and '%i' conversions, if the result doesn't
     start with a plus or minus sign, prefix it with a space character
     instead.  Since the '+' flag ensures that the result includes a
     sign, this flag is ignored if you supply both of them.

'#'
     For the '%o' conversion, this forces the leading digit to be '0',
     as if by increasing the precision.  For '%x' or '%X', this prefixes
     a leading '0x' or '0X' (respectively) to the result.  This doesn't
     do anything useful for the '%d', '%i', or '%u' conversions.

'0'
     Pad the field with zeros instead of spaces.  The zeros are placed
     after any indication of sign or base.  This flag is ignored if the
     '-' flag is also specified, or if a precision is specified.

   If a precision is supplied, it specifies the minimum number of digits
to appear; leading zeros are produced if necessary.  If you don't
specify a precision, the number is printed with as many digits as it
needs.  If you convert a value of zero with an explicit precision of
zero, then no characters at all are produced.


File: octave.info,  Node: Floating-Point Conversions,  Next: Other Output Conversions,  Prev: Integer Conversions,  Up: C-Style I/O Functions

14.2.9 Floating-Point Conversions
---------------------------------

This section discusses the conversion specifications for floating-point
numbers: the '%f', '%e', '%E', '%g', and '%G' conversions.

   The '%f' conversion prints its argument in fixed-point notation,
producing output of the form ['-']DDD'.'DDD, where the number of digits
following the decimal point is controlled by the precision you specify.

   The '%e' conversion prints its argument in exponential notation,
producing output of the form ['-']D'.'DDD'e'['+'|'-']DD.  Again, the
number of digits following the decimal point is controlled by the
precision.  The exponent always contains at least two digits.  The '%E'
conversion is similar but the exponent is marked with the letter 'E'
instead of 'e'.

   The '%g' and '%G' conversions print the argument in the style of '%e'
or '%E' (respectively) if the exponent would be less than -4 or greater
than or equal to the precision; otherwise they use the '%f' style.
Trailing zeros are removed from the fractional portion of the result and
a decimal-point character appears only if it is followed by a digit.

   The following flags can be used to modify the behavior:

'-'
     Left-justify the result in the field.  Normally the result is
     right-justified.

'+'
     Always include a plus or minus sign in the result.

' '
     If the result doesn't start with a plus or minus sign, prefix it
     with a space instead.  Since the '+' flag ensures that the result
     includes a sign, this flag is ignored if you supply both of them.

'#'
     Specifies that the result should always include a decimal point,
     even if no digits follow it.  For the '%g' and '%G' conversions,
     this also forces trailing zeros after the decimal point to be left
     in place where they would otherwise be removed.

'0'
     Pad the field with zeros instead of spaces; the zeros are placed
     after any sign.  This flag is ignored if the '-' flag is also
     specified.

   The precision specifies how many digits follow the decimal-point
character for the '%f', '%e', and '%E' conversions.  For these
conversions, the default precision is '6'.  If the precision is
explicitly '0', this suppresses the decimal point character entirely.
For the '%g' and '%G' conversions, the precision specifies how many
significant digits to print.  Significant digits are the first digit
before the decimal point, and all the digits after it.  If the precision
is '0' or not specified for '%g' or '%G', it is treated like a value of
'1'.  If the value being printed cannot be expressed precisely in the
specified number of digits, the value is rounded to the nearest number
that fits.


File: octave.info,  Node: Other Output Conversions,  Next: Formatted Input,  Prev: Floating-Point Conversions,  Up: C-Style I/O Functions

14.2.10 Other Output Conversions
--------------------------------

This section describes miscellaneous conversions for 'printf'.

   The '%c' conversion prints a single character.  The '-' flag can be
used to specify left-justification in the field, but no other flags are
defined, and no precision or type modifier can be given.  For example:

     printf ("%c%c%c%c%c", "h", "e", "l", "l", "o");

prints 'hello'.

   The '%s' conversion prints a string.  The corresponding argument must
be a string.  A precision can be specified to indicate the maximum
number of characters to write; otherwise characters in the string up to
but not including the terminating null character are written to the
output stream.  The '-' flag can be used to specify left-justification
in the field, but no other flags or type modifiers are defined for this
conversion.  For example:

     printf ("%3s%-6s", "no", "where");

prints ' nowhere ' (note the leading and trailing spaces).


File: octave.info,  Node: Formatted Input,  Next: Input Conversion Syntax,  Prev: Other Output Conversions,  Up: C-Style I/O Functions

14.2.11 Formatted Input
-----------------------

Octave provides the 'scanf', 'fscanf', and 'sscanf' functions to read
formatted input.  There are two forms of each of these functions.  One
can be used to extract vectors of data from a file, and the other is
more 'C-like'.

 -- Built-in Function: [VAL, COUNT, ERRMSG] = fscanf (FID, TEMPLATE,
          SIZE)
 -- Built-in Function: [V1, V2, ..., COUNT, ERRMSG] = fscanf (FID,
          TEMPLATE, "C")
     In the first form, read from FID according to TEMPLATE, returning
     the result in the matrix VAL.

     The optional argument SIZE specifies the amount of data to read and
     may be one of

     'Inf'
          Read as much as possible, returning a column vector.

     'NR'
          Read up to NR elements, returning a column vector.

     '[NR, Inf]'
          Read as much as possible, returning a matrix with NR rows.  If
          the number of elements read is not an exact multiple of NR,
          the last column is padded with zeros.

     '[NR, NC]'
          Read up to 'NR * NC' elements, returning a matrix with NR
          rows.  If the number of elements read is not an exact multiple
          of NR, the last column is padded with zeros.

     If SIZE is omitted, a value of 'Inf' is assumed.

     A string is returned if TEMPLATE specifies only character
     conversions.

     The number of items successfully read is returned in COUNT.

     If an error occurs, ERRMSG contains a system-dependent error
     message.

     In the second form, read from FID according to TEMPLATE, with each
     conversion specifier in TEMPLATE corresponding to a single scalar
     return value.  This form is more "C-like", and also compatible with
     previous versions of Octave.  The number of successful conversions
     is returned in COUNT

     See the Formatted Input section of the GNU Octave manual for a
     complete description of the syntax of the template string.

     See also: *note fgets: XREFfgets, *note fgetl: XREFfgetl, *note
     fread: XREFfread, *note scanf: XREFscanf, *note sscanf: XREFsscanf,
     *note fopen: XREFfopen.

 -- Built-in Function: [VAL, COUNT, ERRMSG] = scanf (TEMPLATE, SIZE)
 -- Built-in Function: [V1, V2, ..., COUNT, ERRMSG]] = scanf (TEMPLATE,
          "C")
     This is equivalent to calling 'fscanf' with FID = 'stdin'.

     It is currently not useful to call 'scanf' in interactive programs.

     See also: *note fscanf: XREFfscanf, *note sscanf: XREFsscanf, *note
     printf: XREFprintf.

 -- Built-in Function: [VAL, COUNT, ERRMSG, POS] = sscanf (STRING,
          TEMPLATE, SIZE)
 -- Built-in Function: [V1, V2, ..., COUNT, ERRMSG] = sscanf (STRING,
          TEMPLATE, "C")
     This is like 'fscanf', except that the characters are taken from
     the string STRING instead of from a stream.  Reaching the end of
     the string is treated as an end-of-file condition.  In addition to
     the values returned by 'fscanf', the index of the next character to
     be read is returned in POS.

     See also: *note fscanf: XREFfscanf, *note scanf: XREFscanf, *note
     sprintf: XREFsprintf.

   Calls to 'scanf' are superficially similar to calls to 'printf' in
that arbitrary arguments are read under the control of a template
string.  While the syntax of the conversion specifications in the
template is very similar to that for 'printf', the interpretation of the
template is oriented more towards free-format input and simple pattern
matching, rather than fixed-field formatting.  For example, most 'scanf'
conversions skip over any amount of "white space" (including spaces,
tabs, and newlines) in the input file, and there is no concept of
precision for the numeric input conversions as there is for the
corresponding output conversions.  Ordinarily, non-whitespace characters
in the template are expected to match characters in the input stream
exactly.

   When a "matching failure" occurs, 'scanf' returns immediately,
leaving the first non-matching character as the next character to be
read from the stream, and 'scanf' returns all the items that were
successfully converted.

   The formatted input functions are not used as frequently as the
formatted output functions.  Partly, this is because it takes some care
to use them properly.  Another reason is that it is difficult to recover
from a matching error.


File: octave.info,  Node: Input Conversion Syntax,  Next: Table of Input Conversions,  Prev: Formatted Input,  Up: C-Style I/O Functions

14.2.12 Input Conversion Syntax
-------------------------------

A 'scanf' template string is a string that contains ordinary multibyte
characters interspersed with conversion specifications that start with
'%'.

   Any whitespace character in the template causes any number of
whitespace characters in the input stream to be read and discarded.  The
whitespace characters that are matched need not be exactly the same
whitespace characters that appear in the template string.  For example,
write ' , ' in the template to recognize a comma with optional
whitespace before and after.

   Other characters in the template string that are not part of
conversion specifications must match characters in the input stream
exactly; if this is not the case, a matching failure occurs.

   The conversion specifications in a 'scanf' template string have the
general form:

     % FLAGS WIDTH TYPE CONVERSION

   In more detail, an input conversion specification consists of an
initial '%' character followed in sequence by:

   * An optional "flag character" '*', which says to ignore the text
     read for this specification.  When 'scanf' finds a conversion
     specification that uses this flag, it reads input as directed by
     the rest of the conversion specification, but it discards this
     input, does not return any value, and does not increment the count
     of successful assignments.

   * An optional decimal integer that specifies the "maximum field
     width".  Reading of characters from the input stream stops either
     when this maximum is reached or when a non-matching character is
     found, whichever happens first.  Most conversions discard initial
     whitespace characters, and these discarded characters don't count
     towards the maximum field width.  Conversions that do not discard
     initial whitespace are explicitly documented.

   * An optional type modifier character.  This character is ignored by
     Octave's 'scanf' function, but is recognized to provide
     compatibility with the C language 'scanf'.

   * A character that specifies the conversion to be applied.

   The exact options that are permitted and how they are interpreted
vary between the different conversion specifiers.  See the descriptions
of the individual conversions for information about the particular
options that they allow.


File: octave.info,  Node: Table of Input Conversions,  Next: Numeric Input Conversions,  Prev: Input Conversion Syntax,  Up: C-Style I/O Functions

14.2.13 Table of Input Conversions
----------------------------------

Here is a table that summarizes the various conversion specifications:

'%d'
     Matches an optionally signed integer written in decimal.  *Note
     Numeric Input Conversions::.

'%i'
     Matches an optionally signed integer in any of the formats that the
     C language defines for specifying an integer constant.  *Note
     Numeric Input Conversions::.

'%o'
     Matches an unsigned integer written in octal radix.  *Note Numeric
     Input Conversions::.

'%u'
     Matches an unsigned integer written in decimal radix.  *Note
     Numeric Input Conversions::.

'%x', '%X'
     Matches an unsigned integer written in hexadecimal radix.  *Note
     Numeric Input Conversions::.

'%e', '%f', '%g', '%E', '%G'
     Matches an optionally signed floating-point number.  *Note Numeric
     Input Conversions::.

'%s'
     Matches a string containing only non-whitespace characters.  *Note
     String Input Conversions::.

'%c'
     Matches a string of one or more characters; the number of
     characters read is controlled by the maximum field width given for
     the conversion.  *Note String Input Conversions::.

'%%'
     This matches a literal '%' character in the input stream.  No
     corresponding argument is used.

   If the syntax of a conversion specification is invalid, the behavior
is undefined.  If there aren't enough function arguments provided to
supply addresses for all the conversion specifications in the template
strings that perform assignments, or if the arguments are not of the
correct types, the behavior is also undefined.  On the other hand, extra
arguments are simply ignored.


File: octave.info,  Node: Numeric Input Conversions,  Next: String Input Conversions,  Prev: Table of Input Conversions,  Up: C-Style I/O Functions

14.2.14 Numeric Input Conversions
---------------------------------

This section describes the 'scanf' conversions for reading numeric
values.

   The '%d' conversion matches an optionally signed integer in decimal
radix.

   The '%i' conversion matches an optionally signed integer in any of
the formats that the C language defines for specifying an integer
constant.

   For example, any of the strings '10', '0xa', or '012' could be read
in as integers under the '%i' conversion.  Each of these specifies a
number with decimal value '10'.

   The '%o', '%u', and '%x' conversions match unsigned integers in
octal, decimal, and hexadecimal radices, respectively.

   The '%X' conversion is identical to the '%x' conversion.  They both
permit either uppercase or lowercase letters to be used as digits.

   Unlike the C language 'scanf', Octave ignores the 'h', 'l', and 'L'
modifiers.


File: octave.info,  Node: String Input Conversions,  Next: Binary I/O,  Prev: Numeric Input Conversions,  Up: C-Style I/O Functions

14.2.15 String Input Conversions
--------------------------------

This section describes the 'scanf' input conversions for reading string
and character values: '%s' and '%c'.

   The '%c' conversion is the simplest: it matches a fixed number of
characters, always.  The maximum field with says how many characters to
read; if you don't specify the maximum, the default is 1.  This
conversion does not skip over initial whitespace characters.  It reads
precisely the next N characters, and fails if it cannot get that many.

   The '%s' conversion matches a string of non-whitespace characters.
It skips and discards initial whitespace, but stops when it encounters
more whitespace after having read something.

   For example, reading the input:

      hello, world

with the conversion '%10c' produces " hello, wo", but reading the same
input with the conversion '%10s' produces "hello,".


File: octave.info,  Node: Binary I/O,  Next: Temporary Files,  Prev: String Input Conversions,  Up: C-Style I/O Functions

14.2.16 Binary I/O
------------------

Octave can read and write binary data using the functions 'fread' and
'fwrite', which are patterned after the standard C functions with the
same names.  They are able to automatically swap the byte order of
integer data and convert among the supported floating point formats as
the data are read.

 -- Built-in Function: [VAL, COUNT] = fread (FID, SIZE, PRECISION, SKIP,
          ARCH)
     Read binary data of type PRECISION from the specified file ID FID.

     The optional argument SIZE specifies the amount of data to read and
     may be one of

     'Inf'
          Read as much as possible, returning a column vector.

     'NR'
          Read up to NR elements, returning a column vector.

     '[NR, Inf]'
          Read as much as possible, returning a matrix with NR rows.  If
          the number of elements read is not an exact multiple of NR,
          the last column is padded with zeros.

     '[NR, NC]'
          Read up to 'NR * NC' elements, returning a matrix with NR
          rows.  If the number of elements read is not an exact multiple
          of NR, the last column is padded with zeros.

     If SIZE is omitted, a value of 'Inf' is assumed.

     The optional argument PRECISION is a string specifying the type of
     data to read and may be one of

     "schar"
     "signed char"
          Signed character.

     "uchar"
     "unsigned char"
          Unsigned character.

     "int8"
     "integer*1"

          8-bit signed integer.

     "int16"
     "integer*2"
          16-bit signed integer.

     "int32"
     "integer*4"
          32-bit signed integer.

     "int64"
     "integer*8"
          64-bit signed integer.

     "uint8"
          8-bit unsigned integer.

     "uint16"
          16-bit unsigned integer.

     "uint32"
          32-bit unsigned integer.

     "uint64"
          64-bit unsigned integer.

     "single"
     "float32"
     "real*4"
          32-bit floating point number.

     "double"
     "float64"
     "real*8"
          64-bit floating point number.

     "char"
     "char*1"
          Single character.

     "short"
          Short integer (size is platform dependent).

     "int"
          Integer (size is platform dependent).

     "long"
          Long integer (size is platform dependent).

     "ushort"
     "unsigned short"
          Unsigned short integer (size is platform dependent).

     "uint"
     "unsigned int"
          Unsigned integer (size is platform dependent).

     "ulong"
     "unsigned long"
          Unsigned long integer (size is platform dependent).

     "float"
          Single precision floating point number (size is platform
          dependent).

     The default precision is "uchar".

     The PRECISION argument may also specify an optional repeat count.
     For example, '32*single' causes 'fread' to read a block of 32
     single precision floating point numbers.  Reading in blocks is
     useful in combination with the SKIP argument.

     The PRECISION argument may also specify a type conversion.  For
     example, 'int16=>int32' causes 'fread' to read 16-bit integer
     values and return an array of 32-bit integer values.  By default,
     'fread' returns a double precision array.  The special form '*TYPE'
     is shorthand for 'TYPE=>TYPE'.

     The conversion and repeat counts may be combined.  For example, the
     specification '32*single=>single' causes 'fread' to read blocks of
     single precision floating point values and return an array of
     single precision values instead of the default array of double
     precision values.

     The optional argument SKIP specifies the number of bytes to skip
     after each element (or block of elements) is read.  If it is not
     specified, a value of 0 is assumed.  If the final block read is not
     complete, the final skip is omitted.  For example,

          fread (f, 10, "3*single=>single", 8)

     will omit the final 8-byte skip because the last read will not be a
     complete block of 3 values.

     The optional argument ARCH is a string specifying the data format
     for the file.  Valid values are

     '"native"'
          The format of the current machine.

     '"ieee-be"'
          IEEE big endian.

     '"ieee-le"'
          IEEE little endian.

     The data read from the file is returned in VAL, and the number of
     values read is returned in 'count'

     See also: *note fwrite: XREFfwrite, *note fgets: XREFfgets, *note
     fgetl: XREFfgetl, *note fscanf: XREFfscanf, *note fopen: XREFfopen.

 -- Built-in Function: COUNT = fwrite (FID, DATA, PRECISION, SKIP, ARCH)
     Write data in binary form of type PRECISION to the specified file
     ID FID, returning the number of values successfully written to the
     file.

     The argument DATA is a matrix of values that are to be written to
     the file.  The values are extracted in column-major order.

     The remaining arguments PRECISION, SKIP, and ARCH are optional, and
     are interpreted as described for 'fread'.

     The behavior of 'fwrite' is undefined if the values in DATA are too
     large to fit in the specified precision.

     See also: *note fread: XREFfread, *note fputs: XREFfputs, *note
     fprintf: XREFfprintf, *note fopen: XREFfopen.


File: octave.info,  Node: Temporary Files,  Next: EOF and Errors,  Prev: Binary I/O,  Up: C-Style I/O Functions

14.2.17 Temporary Files
-----------------------

Sometimes one needs to write data to a file that is only temporary.
This is most commonly used when an external program launched from within
Octave needs to access data.  When Octave exits all temporary files will
be deleted, so this step need not be executed manually.

 -- Built-in Function: [FID, NAME, MSG] = mkstemp (TEMPLATE, DELETE)
     Return the file ID corresponding to a new temporary file with a
     unique name created from TEMPLATE.  The last six characters of
     TEMPLATE must be 'XXXXXX' and these are replaced with a string that
     makes the filename unique.  The file is then created with mode
     read/write and permissions that are system dependent (on GNU/Linux
     systems, the permissions will be 0600 for versions of glibc 2.0.7
     and later).  The file is opened in binary mode and with the 'O_EXCL'
     flag.

     If the optional argument DELETE is supplied and is true, the file
     will be deleted automatically when Octave exits.

     If successful, FID is a valid file ID, NAME is the name of the
     file, and MSG is an empty string.  Otherwise, FID is -1, NAME is
     empty, and MSG contains a system-dependent error message.

     See also: *note tmpfile: XREFtmpfile, *note tmpnam: XREFtmpnam,
     *note P_tmpdir: XREFP_tmpdir.

 -- Built-in Function: [FID, MSG] = tmpfile ()
     Return the file ID corresponding to a new temporary file with a
     unique name.  The file is opened in binary read/write ("w+b") mode.
     The file will be deleted automatically when it is closed or when
     Octave exits.

     If successful, FID is a valid file ID and MSG is an empty string.
     Otherwise, FID is -1 and MSG contains a system-dependent error
     message.

     See also: *note tmpnam: XREFtmpnam, *note mkstemp: XREFmkstemp,
     *note P_tmpdir: XREFP_tmpdir.

 -- Built-in Function: tmpnam ()
 -- Built-in Function: tmpnam (DIR)
 -- Built-in Function: tmpnam (DIR, PREFIX)
     Return a unique temporary file name as a string.

     If PREFIX is omitted, a value of "oct-" is used.  If DIR is also
     omitted, the default directory for temporary files is used.  If DIR
     is provided, it must exist, otherwise the default directory for
     temporary files is used.  Since the named file is not opened, by
     'tmpnam', it is possible (though relatively unlikely) that it will
     not be available by the time your program attempts to open it.

     See also: *note tmpfile: XREFtmpfile, *note mkstemp: XREFmkstemp,
     *note P_tmpdir: XREFP_tmpdir.

