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

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

END-INFO-DIR-ENTRY

   Copyright (C) 1996, 1997, 1999, 2000, 2001, 2002, 2005, 2006, 2007,
2011 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: 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 iff

       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: doc-ne, *note isequal: doc-isequal.

 -- Built-in Function:  ge (X, Y)
     This function is equivalent to `x >= y'.

 -- Built-in Function:  gt (X, Y)
     This function is equivalent to `x > y'.

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

     *See also:* *note isequalwithequalnans: doc-isequalwithequalnans.

 -- Function File:  isequalwithequalnans (X1, X2, ...)
     Assuming NaN == NaN, return true if all of X1, X2, ...  are equal.

     *See also:* *note isequal: doc-isequal.

 -- Built-in Function:  le (X, Y)
     This function is equivalent to `x <= y'.

 -- Built-in Function:  lt (X, Y)
     This function is equivalent to `x < y'.

 -- 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: doc-eq, *note isequal: doc-isequal.


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: doc-or, *note not: doc-not, *note xor:
     doc-xor.

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

     *See also:* *note and: doc-and, *note or: doc-or, *note xor:
     doc-xor.

 -- 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: doc-and, *note not: doc-not, *note xor:
     doc-xor.


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


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 makes the variable A with the approximate
     value 3.1416 available.

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

     If an error occurs during the evaluation of TRY 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

     Consider using try/catch blocks instead if you are only using
     `eval' as an error-capturing mechanism rather than for the
     execution of arbitrary code strings.

     *See also:* *note evalin: doc-evalin.

* 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 example, for a list of predicates for numeric objects,
and see *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 on 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 that F is a function handle or the
     function name in a string, `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 scripts in the current workspace that are not necessarily on
     the path.  If SCRIPT is the script to run, including its path, then
     `run' changes the directory to the directory where SCRIPT is
     found.  `run' then executes the script, and returns to the original
     directory.

     *See also:* *note system: doc-system.


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: doc-eval, *note assignin: doc-assignin.

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


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 `for' or `while' 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 `for' or
`while' 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 modelled 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.


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

10.9 The `try' Statement
========================

In addition to unwind_protect, Octave supports another limited form of
exception handling.

   The general 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 function `lasterr' to access the text of the message that would
have been printed.  This is the same as `eval (TRY, CATCH)' but it is
more efficient since the commands do not need to be parsed each time
the TRY and CATCH statements are evaluated.  *Note Errors and
Warnings::, for more information about the `lasterr' function.


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 `...' or `\' 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.  The backslash character on the second line
above is interpreted as a continuation character, _not_ as a division
operator.

   For continuation lines that do not occur inside string constants,
whitespace and comments may appear between the continuation marker and
the newline character.  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 string constants, the
continuation marker must appear at the end of the line just before the
newline character.

   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:

* 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 Inline Functions and Anonymous Functions::
* Commands::
* Organization of Functions::


File: octave.info,  Node: Defining Functions,  Next: Multiple Return Values,  Up: Functions and Scripts

11.1 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_NAME)
     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_NAME, return the maximum number of arguments the named
     function can accept, or -1 if the function accepts a variable
     number of arguments.

     *See also:* *note nargout: doc-nargout, *note varargin:
     doc-varargin, *note isargout: doc-isargout, *note varargout:
     doc-varargout, *note nthargout: doc-nthargout.

 -- 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.2 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: doc-nargin, *note nargout: doc-nargout,
     *note varargin: doc-varargin, *note varargout: doc-varargout,
     *note isargout: doc-isargout.

   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_NAME)
     Within a function, return the number of values the caller expects
     to receive.  If called with the optional argument FCN_NAME, return
     the maximum number of values the named function can produce, or -1
     if the function can produce a variable number of values.

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

     At the top level, `nargout' is undefined.

     *See also:* *note nargin: doc-nargin, *note varargin:
     doc-varargin, *note isargout: doc-isargout, *note varargout:
     doc-varargout, *note nthargout: doc-nthargout.

   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: doc-nargoutchk, *note narginchk:
     doc-narginchk, *note error: doc-error, *note nargin: doc-nargin,
     *note nargout: doc-nargout.

 -- 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: doc-nargchk, *note nargoutchk:
     doc-nargoutchk, *note error: doc-error, *note nargout:
     doc-nargout, *note nargin: doc-nargin.

 -- 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: doc-nargchk, *note narginchk:
     doc-narginchk, *note error: doc-error, *note nargout: doc-nargout,
     *note nargin: doc-nargin.


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

11.3 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'
     arguments and 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: doc-varargin.


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

11.4 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 on output to a variable.  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: doc-nargout, *note nargin: doc-nargin,
     *note varargin: doc-varargin, *note varargout: doc-varargout,
     *note nthargout: doc-nthargout.


File: octave.info,  Node: Variable-length Return Lists,  Next: Returning from a Function,  Prev: Ignoring Arguments,  Up: Functions and Scripts

11.5 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.6 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.7 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.8 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 a text 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 further down) 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 `HOME'.  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 `HOME/name.ext' 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 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 VALUE.  If an output argument is
     requested and the first 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:

    `editor'
          This is the editor to use to modify the functions.  By
          default it uses Octave's `EDITOR' built-in function, which
          comes from `getenv("EDITOR")' and defaults to `emacs'.  Use
          `%s' In place of the function name.  For example,
         `[EDITOR, " %s"]'
               Use the editor which Octave uses for `edit_history'.

         `"xedit %s &"'
               pop up simple X11 editor in a separate window

         `"gnudoit -q \"(find-file \\\"%s\\\")\""'
               Send it to current Emacs; must have `(gnuserv-start)' in
               `.emacs'.

          See also field 'mode', which controls how the editor is run
          by Octave.

          On Cygwin, you will need to convert the Cygwin path to a
          Windows path if you are using a native Windows editor.  For
          example:

          '"C:/Program Files/Good Editor/Editor.exe" "$(cygpath -wa %s)"'


    `home'
          This is the location of user local m-files.  Be 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
          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 `<user@host>'
          as your format.

    `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" (see also "system").

    `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.  At the top-level,
     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::
* 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.8.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 DIR1, ... to the current 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: doc-path, *note rmpath: doc-rmpath, *note
     genpath: doc-genpath, *note pathdef: doc-pathdef, *note savepath:
     doc-savepath, *note pathsep: doc-pathsep.

 -- 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: doc-path, *note addpath: doc-addpath,
     *note genpath: doc-genpath, *note pathdef: doc-pathdef, *note
     savepath: doc-savepath, *note pathsep: doc-pathsep.

 -- Function File:  savepath (FILE)
     Save the 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: doc-path, *note addpath: doc-addpath,
     *note rmpath: doc-rmpath, *note genpath: doc-genpath, *note
     pathdef: doc-pathdef, *note pathsep: doc-pathsep.

 -- 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: doc-addpath, *note rmpath: doc-rmpath,
     *note genpath: doc-genpath, *note pathdef: doc-pathdef, *note
     savepath: doc-savepath, *note pathsep: doc-pathsep.

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

       1. `~/.octaverc'

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

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

     *See also:* *note path: doc-path, *note addpath: doc-addpath,
     *note rmpath: doc-rmpath, *note genpath: doc-genpath, *note
     savepath: doc-savepath, *note pathsep: doc-pathsep.

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

 -- 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: doc-file_in_path, *note path:
     doc-path.

 -- Built-in Function:  restoredefaultpath (...)
     Restore Octave's path to its initial state at startup.

     *See also:* *note path: doc-path, *note addpath: doc-addpath,
     *note rmpath: doc-rmpath, *note genpath: doc-genpath, *note
     pathdef: doc-pathdef, *note savepath: doc-savepath, *note pathsep:
     doc-pathsep.

 -- Built-in Function:  command_line_path (...)
     Return the command line path variable.

     *See also:* *note path: doc-path, *note addpath: doc-addpath,
     *note rmpath: doc-rmpath, *note genpath: doc-genpath, *note
     pathdef: doc-pathdef, *note savepath: doc-savepath, *note pathsep:
     doc-pathsep.

 -- 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"' or `"/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.


File: octave.info,  Node: Subfunctions,  Next: Private Functions,  Prev: Manipulating the Load Path,  Up: Function Files

11.8.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: Overloading and Autoloading,  Prev: Subfunctions,  Up: Function Files

11.8.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: Overloading and Autoloading,  Next: Function Locking,  Prev: Private Functions,  Up: Function Files

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

 -- Loadable Function: [...] builtin (F, ...)
     Call the base function F even if F is overloaded to another
     function for the given type signature.

   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 (FUNCTION, FILE)
     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 the 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
     when `bar.oct' is not in the same directory or uses like

          autoload ("foo", file_in_loadpath ("bar.oct"))

     are strongly discouraged, as their behavior might be unpredictable.

     With no arguments, return a structure containing the current
     autoload map.

     *See also:* *note PKG_ADD: doc-PKG_ADD.


File: octave.info,  Node: Function Locking,  Next: Function Precedence,  Prev: Overloading and Autoloading,  Up: Function Files

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

     mlock ("my_function");

prevents `my_function' from being removed from memory, 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.

     mlock ("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()
       persistent calls = 0;
       printf ("'count_calls' has been called %d times\n",
               ++calls);
     endfunction
     mlock ("count_calls");

     count_calls ();
     -| 'count_calls' has been called 1 times

     clear count_calls
     count_calls ();
     -| 'count_calls' has been called 2 times

It is, however, often inconvenient to lock a function from the prompt,
so it is also possible to lock a function from within its body.  This
is simply done by calling `mlock' from within the function.

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

   `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: doc-munlock, *note mislocked:
     doc-mislocked, *note persistent: doc-persistent.

 -- 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: doc-mlock, *note mislocked:
     doc-mislocked, *note persistent: doc-persistent.

 -- 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: doc-mlock, *note munlock: doc-munlock,
     *note persistent: doc-persistent.


File: octave.info,  Node: Function Precedence,  Prev: Function Locking,  Up: Function Files

11.8.6 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. Legacy Dispatch An overloaded function as defined by `dispatch'.

  6. Command-line Function A function that has been defined on the
     command-line.

  7. Autoload function A function that is marked as autoloaded with
     *Note doc-autoload::.

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

  9. Built-in function A function that is builtin to Octave itself such
     as `numel', `size', etc.


File: octave.info,  Node: Script Files,  Next: Function Handles Inline Functions and Anonymous Functions,  Prev: Function Files,  Up: Functions and Scripts

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


File: octave.info,  Node: Function Handles Inline Functions and Anonymous Functions,  Next: Commands,  Prev: Script Files,  Up: Functions and Scripts

11.10 Function Handles, Inline Functions, and Anonymous 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 Inline Functions and Anonymous Functions

11.10.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: doc-isa, *note typeinfo: doc-typeinfo,
     *note class: doc-class.

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

 -- Built-in Function:  func2str (FCN_HANDLE)
     Return a string containing the name of the function referenced by
     the function handle FCN_HANDLE.

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


File: octave.info,  Node: Anonymous Functions,  Next: Inline Functions,  Prev: Function Handles,  Up: Function Handles Inline Functions and Anonymous Functions

11.10.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 Inline Functions and Anonymous Functions

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

     *See also:* *note argnames: doc-argnames, *note formula:
     doc-formula, *note vectorize: doc-vectorize.

 -- 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: doc-inline, *note formula: doc-formula,
     *note vectorize: doc-vectorize.

 -- 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: doc-argnames, *note inline:
     doc-inline, *note vectorize: doc-vectorize.

 -- 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 Inline Functions and Anonymous Functions,  Up: Functions and Scripts

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

   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 on-line 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: doc-help.

 -- 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: doc-puts, *note fputs: doc-fputs, *note
     printf: doc-printf, *note fprintf: doc-fprintf.

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

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

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

   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: doc-lasterror, *note lasterr:
     doc-lasterr, *note error: doc-error.

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

 -- Loadable Function: C = onCleanup (ACTION)
     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, ACTION
     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.

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

     *See also:* *note warning_ids: doc-warning_ids.

 -- Built-in Function: [MSG, MSGID] = lastwarn (MSG, MSGID)
     Without any arguments, return the last warning message.  With one
     argument, set the last warning message to MSG.  With two arguments,
     also set the last message identifier.


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 ("non-negative-variable",
              "'a' must be non-negative.  Setting 'a' to zero.");

while the following won't issue a warning

     warning ("off", "non-negative-variable");
     warning ("non-negative-variable",
              "'a' must be non-negative.  Setting 'a' to zero.");

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

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

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

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


File: octave.info,  Node: Leaving Debug Mode,  Next: Breakpoints,  Prev: Entering Debug Mode,  Up: Debugging

13.2 Leaving Debug Mode
=======================

To leave the debug mode, use either `dbcont' or `return'.

 -- Command:  dbcont
     Leave command-line debugging mode and continue code execution
     normally.

     *See also:* *note dbstep: doc-dbstep, *note dbquit: doc-dbquit.

   To quit debug mode and return directly to the prompt `dbquit' should
be used instead

 -- Command:  dbquit
     Quit debugging mode immediately without further code execution and
     return to the Octave prompt.

     *See also:* *note dbcont: doc-dbcont, *note dbstep: doc-dbstep.

   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 Octave function, using the `dbstop'
function.

 -- Loadable Function: RLINE = dbstop ("FUNC")
 -- Loadable Function: RLINE = dbstop ("FUNC", LINE, ...)
     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: doc-dbclear, *note dbstatus:
     doc-dbstatus, *note dbstep: doc-dbstep, *note debug_on_error:
     doc-debug_on_error, *note debug_on_warning: doc-debug_on_warning,
     *note debug_on_interrupt: doc-debug_on_interrupt.

Note that breakpoints cannot be set in built-in functions (e.g., `sin',
etc.) or dynamically loaded function (i.e., oct-files).  To set a
breakpoint immediately on entering a function, the breakpoint should be
set to line 1. The leading comment block will be ignored and the
breakpoint will be set to the first executable statement in the
function.  For example:

     dbstop ("asind", 1)
     => 28

Note that the return value of `27' means that the breakpoint was
effectively set to line 27.  The status of breakpoints in a function can
be queried with the `dbstatus' function.

 -- Loadable Function:  dbstatus ()
 -- Loadable Function: BRK_LIST = dbstatus ()
 -- Loadable 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: doc-dbclear, *note dbwhere: doc-dbwhere.

Taking the above as an example, `dbstatus ("asind")' should return 28.
The breakpoints can then be cleared with the `dbclear' function

 -- Loadable Function:  dbclear ("FUNC")
 -- Loadable Function:  dbclear ("FUNC", LINE, ...)
     Delete a breakpoint in the 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 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: doc-dbstop, *note dbstatus:
     doc-dbstatus, *note dbwhere: doc-dbwhere.

These functions can be used to clear all the breakpoints in a function.
For example:

     dbclear ("asind", dbstatus ("asind"));

   A breakpoint can 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 a character that marks the
subfunctions from the file containing them.

   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: doc-dbcont, *note dbquit: doc-dbquit.

The `keyboard' function is typically placed in a script at the point
where the user desires that the execution is 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 two additional support functions that allow the user to
interrogate 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.

 -- Loadable Function:  dbwhere ()
     In debugging mode, report the current file and line number where
     execution is stopped.

     *See also:* *note dbstatus: doc-dbstatus, *note dbcont:
     doc-dbcont, *note dbstep: doc-dbstep, *note dbup: doc-dbup.

 -- Loadable Function:  dbtype ()
 -- Loadable Function:  dbtype ("startl:endl")
 -- Loadable Function:  dbtype ("FUNC")
 -- Loadable Function:  dbtype ("FUNC", "startl:endl")
     When in debugging mode and called with no arguments, list the
     script file being debugged with line numbers.  An optional range
     specification, specified as a string, can be used to list only a
     portion of the file.

     When called with the name of a function, list that script file
     with line numbers.

     *See also:* *note dbstatus: doc-dbstatus, *note dbstop: doc-dbstop.

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

 -- Loadable Function:  isdebugmode ()
     Return true if in debugging mode, otherwise false.

     *See also:* *note dbwhere: doc-dbwhere, *note dbstack:
     doc-dbstack, *note dbstatus: doc-dbstatus.

   Debug mode also allows single line stepping through a function using
the commands `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: doc-dbcont, *note dbquit: doc-dbquit.


File: octave.info,  Node: Call Stack,  Next: Profiling,  Prev: Debug Mode,  Up: Debugging

13.5 Call Stack
===============

 -- Loadable Function:  dbstack ()
 -- Loadable Function:  dbstack (N)
 -- Loadable Function: [STACK, IDX] = dbstack (...)
     Display or return current debugging function stack information.
     With optional argument N, omit the N innermost stack frames.

     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: doc-dbup, *note dbdown: doc-dbdown, *note
     dbwhere: doc-dbwhere, *note dbstatus: doc-dbstatus.

 -- Loadable Function:  dbup
 -- Loadable 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: doc-dbstack, *note dbdown: doc-dbdown.

 -- Loadable Function:  dbdown
 -- Loadable 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: doc-dbstack, *note dbup: doc-dbup.


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: doc-profshow, *note profexplore:
          doc-profexplore.

   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: doc-profexplore, *note profile:
     doc-profile.

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

     *See also:* *note profile: doc-profile, *note profshow:
     doc-profshow.


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.  See also
*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 modelled 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: doc-fdisp.

 -- Built-in Function:  list_in_columns (ARG, WIDTH)
     Return a string containing the elements of ARG listed in columns
     with an overall maximum width of WIDTH.  The argument ARG must be
     a cell array of character strings or a character array.  If WIDTH
     is not specified, 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)
               => ans = 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: doc-terminal_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: doc-list_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: doc-fixed_point_format,
     *note output_max_field_width: doc-output_max_field_width, *note
     output_precision: doc-output_precision, *note split_long_rows:
     doc-split_long_rows, *note rats: doc-rats.

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

 -- 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 more: doc-more, *note page_screen_output:
     doc-page_screen_output, *note page_output_immediately:
     doc-page_output_immediately, *note PAGER_FLAGS: doc-PAGER_FLAGS.

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

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

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

 -- 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: doc-fopen, *note fclose: doc-fclose.


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:  input (PROMPT)
 -- Built-in Function:  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.  *Note Input and Output::.

 -- 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: doc-disp, *note printf: doc-printf, *note
     input: doc-input.

 -- Built-in Function:  yes_or_no (PROMPT)
     Ask the user a yes-or-no question.  Return 1 if the answer is yes.
     Takes one argument, which is the string to display to ask the
     question.  It should end in a space; `yes-or-no-p' adds `(yes or
     no) ' to it.  The user must confirm the answer with RET and can
     edit it until it has been confirmed.

   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 ()
     Read a single keystroke from the keyboard.  If called with one
     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);

     identical to the above example, but don't wait for a keypress,
     returning the empty string if no key is available.


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
`default_save_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 `default_save_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: doc-load, *note default_save_options:
     doc-default_save_options, *note save_header_format_string:
     doc-save_header_format_string, *note dlmread: doc-dlmread, *note
     csvread: doc-csvread, *note fread: doc-fread.

 -- 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: doc-save, *note dlmwrite: doc-dlmwrite,
     *note csvwrite: doc-csvwrite, *note fwrite: doc-fwrite.

 -- Function File: STR = fileread (FILENAME)
     Read the contents of FILENAME and return it as a string.

     *See also:* *note fread: doc-fread, *note textread: doc-textread,
     *note sscanf: doc-sscanf.

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

 -- Built-in Function: VAL = default_save_options ()
 -- Built-in Function: OLD_VAL = default_save_options (NEW_VAL)
 -- Built-in Function:  default_save_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: doc-save.

 -- 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: doc-strftime, *note save: doc-save.

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

   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: doc-dlmread, *note csvread:
     doc-csvread, *note csvwrite: doc-csvwrite.

 -- Loadable Function: DATA = dlmread (FILE)
 -- Loadable Function: DATA = dlmread (FILE, SEP)
 -- Loadable Function: DATA = dlmread (FILE, SEP, R0, C0)
 -- Loadable Function: DATA = dlmread (FILE, SEP, RANGE)
 -- Loadable 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: doc-csvread, *note textscan:
     doc-textscan, *note textread: doc-textread, *note dlmwrite:
     doc-dlmwrite.

 -- 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: doc-csvread, *note dlmwrite:
     doc-dlmwrite, *note dlmread: doc-dlmread.

 -- 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: doc-csvwrite, *note dlmread:
     doc-dlmread, *note dlmwrite: doc-dlmwrite.

   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 specifes the number of times to use FORMAT
     when parsing, i.e., the format repeat count.

     *See also:* *note strread: doc-strread, *note load: doc-load,
     *note dlmread: doc-dlmread, *note fscanf: doc-fscanf, *note
     textscan: doc-textscan.

 -- 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 file associated with FID 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 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.

     The optional input N specifes the number of times to use FORMAT
     when parsing, i.e., the format repeat count.

     The output C is a cell array whose length is given by the number
     of format specifiers.

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

     *See also:* *note dlmread: doc-dlmread, *note fscanf: doc-fscanf,
     *note load: doc-load, *note strread: doc-strread, *note textread:
     doc-textread.

* 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-core' 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-core" 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:
     doc-octave_core_file_limit, *note octave_core_file_name:
     doc-octave_core_file_name, *note octave_core_file_options:
     doc-octave_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-core" 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-core" 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:
     doc-crash_dumps_octave_core, *note octave_core_file_name:
     doc-octave_core_file_name, *note octave_core_file_limit:
     doc-octave_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:
     doc-crash_dumps_octave_core, *note octave_core_file_name:
     doc-octave_core_file_name, *note octave_core_file_options:
     doc-octave_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-core"'

     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:
     doc-crash_dumps_octave_core, *note octave_core_file_name:
     doc-octave_core_file_name, *note octave_core_file_options:
     doc-octave_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: doc-stdout, *note stderr: doc-stderr.

 -- 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: doc-stdin, *note stderr: doc-stderr.

 -- 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: doc-stdin, *note stdout: doc-stdout.

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

          `vaxd' VAX D floating format.

          `vaxg' VAX G floating format.

          `cray' Cray floating format.

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

     *See also:* *note fclose: doc-fclose, *note fgets: doc-fgets,
     *note fputs: doc-fputs, *note fread: doc-fread, *note fseek:
     doc-fseek, *note ferror: doc-ferror, *note fprintf: doc-fprintf,
     *note fscanf: doc-fscanf, *note ftell: doc-ftell, *note fwrite:
     doc-fwrite.

 -- 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: doc-fopen, *note fseek: doc-fseek, *note
     ftell: doc-ftell.

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

     *See also:* *note fopen: doc-fopen.


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 scanf: doc-scanf, *note sscanf: doc-sscanf,
     *note fread: doc-fread, *note fprintf: doc-fprintf, *note fgets:
     doc-fgets, *note fscanf: doc-fscanf.

   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.


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

     *See also:* *note fread: doc-fread, *note fscanf: doc-fscanf.

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

     *See also:* *note fputs: doc-fputs, *note fopen: doc-fopen, *note
     fread: doc-fread, *note fscanf: doc-fscanf.

 -- Built-in Function:  fskipl (FID, COUNT)
     Skip a given number of lines, i.e., discards characters until an
     end-of-line is met exactly COUNT-times, or end-of-file occurs.
     Returns the number of lines skipped (end-of-line sequences
     encountered).  If COUNT is omitted, it defaults to 1. COUNT may
     also be `Inf', in which case lines are skipped to the end of file.
     This form is suitable for counting lines in a file.

     *See also:* *note fgetl: doc-fgetl, *note fgets: doc-fgets.


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
modelled 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: doc-fprintf, *note sprintf:
     doc-sprintf, *note scanf: doc-scanf.

 -- 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 printf: doc-printf, *note sprintf: doc-sprintf,
     *note fread: doc-fread, *note fscanf: doc-fscanf, *note fopen:
     doc-fopen, *note fclose: doc-fclose.

 -- 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: doc-printf, *note fprintf: doc-fprintf,
     *note sscanf: doc-sscanf.

   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 scanf: doc-scanf, *note sscanf: doc-sscanf,
     *note fread: doc-fread, *note fprintf: doc-fprintf, *note fgets:
     doc-fgets, *note fputs: doc-fputs.

 -- 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: doc-fscanf, *note sscanf: doc-sscanf,
     *note printf: doc-printf.

 -- 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: doc-fscanf, *note scanf: doc-scanf,
     *note sprintf: doc-sprintf.

   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.

    `"vaxd"'
          VAX D floating format.

    `"vaxg"'
          VAX G floating format.

    `"cray"'
          Cray floating format.

     Conversions are currently only supported for `"ieee-be"' and
     `"ieee-le"' formats.

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

     *See also:* *note fwrite: doc-fwrite, *note fopen: doc-fopen,
     *note fclose: doc-fclose.

 -- 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: doc-fread, *note fopen: doc-fopen, *note
     fclose: doc-fclose.


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, or when the
     function `purge_tmp_files' is called.

     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: doc-tmpfile, *note tmpnam: doc-tmpnam,
     *note P_tmpdir: doc-P_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: doc-tmpnam, *note mkstemp: doc-mkstemp,
     *note P_tmpdir: doc-P_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: doc-tmpfile, *note mkstemp:
     doc-mkstemp, *note P_tmpdir: doc-P_tmpdir.


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

14.2.18 End of File and Errors
------------------------------

Once a file has been opened its status can be acquired.  As an example
the `feof' functions determines if the end of the file has been
reached.  This can be very useful when reading small parts of a file at
a time.  The following example shows how to read one line at a time
from a file until the end has been reached.

     filename = "myfile.txt";
     fid = fopen (filename, "r");
     while (! feof (fid) )
       text_line = fgetl (fid);
     endwhile
     fclose (fid);

Note that in some situations it is more efficient to read the entire
contents of a file and then process it, than it is to read it line by
line.  This has the potential advantage of removing the loop in the
above code.

 -- Built-in Function:  feof (FID)
     Return 1 if an end-of-file condition has been encountered for a
     given file and 0 otherwise.  Note that it will only return 1 if
     the end of the file has already been encountered, not if the next
     read operation will result in an end-of-file condition.

     *See also:* *note fread: doc-fread, *note fopen: doc-fopen, *note
     fclose: doc-fclose.

 -- Built-in Function: [ERR, MSG] = ferror (FID, "clear")
     Return 1 if an error condition has been encountered for the file ID
     FID and 0 otherwise.  Note that it will only return 1 if an error
     has already been encountered, not if the next operation will
     result in an error condition.

     The second argument is optional.  If it is supplied, also clear the
     error condition.

 -- Built-in Function:  fclear (FID)
     Clear the stream state for the specified file.

 -- Built-in Function:  freport ()
     Print a list of which files have been opened, and whether they are
     open for reading, writing, or both.  For example:

          freport ()

               -|  number  mode  name
               -|
               -|       0     r  stdin
               -|       1     w  stdout
               -|       2     w  stderr
               -|       3     r  myfile


File: octave.info,  Node: File Positioning,  Prev: EOF and Errors,  Up: C-Style I/O Functions

14.2.19 File Positioning
------------------------

Three functions are available for setting and determining the position
of the file pointer for a given file.

 -- Built-in Function:  ftell (FID)
     Return the position of the file pointer as the number of characters
     from the beginning of the file FID.

     *See also:* *note fseek: doc-fseek, *note fopen: doc-fopen, *note
     fclose: doc-fclose.

 -- Built-in Function:  fseek (FID, OFFSET, ORIGIN)
     Set the file pointer to any location within the file FID.

     The pointer is positioned OFFSET characters from the ORIGIN, which
     may be one of the predefined variables `SEEK_CUR' (current
     position), `SEEK_SET' (beginning), or `SEEK_END' (end of file) or
     strings "cof", "bof" or "eof".  If ORIGIN is omitted, `SEEK_SET'
     is assumed.  The offset must be zero, or a value returned by
     `ftell' (in which case ORIGIN must be `SEEK_SET').

     Return 0 on success and -1 on error.

     *See also:* *note ftell: doc-ftell, *note fopen: doc-fopen, *note
     fclose: doc-fclose.

 -- Built-in Function:  SEEK_SET ()
 -- Built-in Function:  SEEK_CUR ()
 -- Built-in Function:  SEEK_END ()
     Return the numerical value to pass to `fseek' to perform one of
     the following actions:
    `SEEK_SET'
          Position file relative to the beginning.

    `SEEK_CUR'
          Position file relative to the current position.

    `SEEK_END'
          Position file relative to the end.

     *See also:* *note fseek: doc-fseek.

 -- Built-in Function:  frewind (FID)
     Move the file pointer to the beginning of the file FID, returning
     0 for success, and -1 if an error was encountered.  It is
     equivalent to `fseek (FID, 0, SEEK_SET)'.

   The following example stores the current file position in the
variable `marker', moves the pointer to the beginning of the file, reads
four characters, and then returns to the original position.

     marker = ftell (myfile);
     frewind (myfile);
     fourch = fgets (myfile, 4);
     fseek (myfile, marker, SEEK_SET);


File: octave.info,  Node: Plotting,  Next: Matrix Manipulation,  Prev: Input and Output,  Up: Top

15 Plotting
***********

* Menu:

* Introduction to Plotting::
* High-Level Plotting::
* Graphics Data Structures::
* Advanced Plotting::


File: octave.info,  Node: Introduction to Plotting,  Next: High-Level Plotting,  Up: Plotting

15.1 Introduction to Plotting
=============================

Earlier versions of Octave provided plotting through the use of
gnuplot.  This capability is still available.  But, a newer plotting
capability is provided by access to OpenGL.  Which plotting system is
used is controlled by the `graphics_toolkit' function.  (See *note
Graphics Toolkits::.)

   The function call `graphics_toolkit ("fltk")' selects the
FLTK/OpenGL system, and `graphics_toolkit ("gnuplot")' selects the
gnuplot system.  The two systems may be used selectively through the use
of the `graphics_toolkit' property of the graphics handle for each
figure.  This is explained in *note Graphics Data Structures::.
*Caution:* The FLTK toolkit uses single precision variables internally
which limits the maximum value that can be displayed to approximately
10^38.  If your data contains larger values you must use the gnuplot
toolkit which supports values up to 10^308.


File: octave.info,  Node: High-Level Plotting,  Next: Graphics Data Structures,  Prev: Introduction to Plotting,  Up: Plotting

15.2 High-Level Plotting
========================

Octave provides simple means to create many different types of two- and
three-dimensional plots using high-level functions.

   If you need more detailed control, see *note Graphics Data
Structures:: and *note Advanced Plotting::.

* Menu:

* Two-Dimensional Plots::
* Three-Dimensional Plots::
* Plot Annotations::
* Multiple Plots on One Page::
* Multiple Plot Windows::
* Printing and Saving Plots::
* Interacting with Plots::
* Test Plotting Functions::


File: octave.info,  Node: Two-Dimensional Plots,  Next: Three-Dimensional Plots,  Up: High-Level Plotting

15.2.1 Two-Dimensional Plots
----------------------------

* Menu:

* Axis Configuration::
* Two-dimensional Function Plotting::
* Two-dimensional Geometric Shapes::

   The `plot' function allows you to create simple x-y plots with
linear axes.  For example,

     x = -10:0.1:10;
     plot (x, sin (x));

displays a sine wave shown in *note fig:plot::.  On most systems, this
command will open a separate plot window to display the graph.


+---------------------------------+
| Image unavailable in text mode. |
+---------------------------------+
Figure 15.1: Simple Two-Dimensional Plot.

 -- Function File:  plot (Y)
 -- Function File:  plot (X, Y)
 -- Function File:  plot (X, Y, PROPERTY, VALUE, ...)
 -- Function File:  plot (X, Y, FMT)
 -- Function File:  plot (H, ...)
 -- Function File: H = plot (...)
     Produce two-dimensional plots.

     Many different combinations of arguments are possible.  The
     simplest form is

          plot (Y)

     where the argument is taken as the set of Y coordinates and the X
     coordinates are taken to be the indices of the elements starting
     with 1.

     To save a plot, in one of several image formats such as PostScript
     or PNG, use the `print' command.

     If more than one argument is given, they are interpreted as

          plot (Y, PROPERTY, VALUE, ...)

     or

          plot (X, Y, PROPERTY, VALUE, ...)

     or

          plot (X, Y, FMT, ...)

     and so on.  Any number of argument sets may appear.  The X and Y
     values are interpreted as follows:

        * If a single data argument is supplied, it is taken as the set
          of Y coordinates and the X coordinates are taken to be the
          indices of the elements, starting with 1.

        * If the X is a vector and Y is a matrix, then the columns (or
          rows) of Y are plotted versus X.  (using whichever
          combination matches, with columns tried first.)

        * If the X is a matrix and Y is a vector, Y is plotted versus
          the columns (or rows) of X.  (using whichever combination
          matches, with columns tried first.)

        * If both arguments are vectors, the elements of Y are plotted
          versus the elements of X.

        * If both arguments are matrices, the columns of Y are plotted
          versus the columns of X.  In this case, both matrices must
          have the same number of rows and columns and no attempt is
          made to transpose the arguments to make the number of rows
          match.

          If both arguments are scalars, a single point is plotted.

     Multiple property-value pairs may be specified, but they must
     appear in pairs.  These arguments are applied to the lines drawn by
     `plot'.

     If the FMT argument is supplied, it is interpreted as follows.  If
     FMT is missing, the default gnuplot line style is assumed.

    `-'
          Set lines plot style (default).

    `.'
          Set dots plot style.

    `N'
          Interpreted as the plot color if N is an integer in the range
          1 to 6.

    `NM'
          If NM is a two digit integer and M is an integer in the range
          1 to 6, M is interpreted as the point style.  This is only
          valid in combination with the `@' or `-@' specifiers.

    `C'
          If C is one of `"k"' (black), `"r"' (red), `"g"' (green),
          `"b"' (blue), `"m"' (magenta), `"c"' (cyan), or `"w"'
          (white), it is interpreted as the line plot color.

    `";title;"'
          Here `"title"' is the label for the key.

    `+'
    `*'
    `o'
    `x'
    `^'
          Used in combination with the points or linespoints styles,
          set the point style.

    `@'
          Select the next unused point style.

     The FMT argument may also be used to assign key titles.  To do so,
     include the desired title between semi-colons after the formatting
     sequence described above, e.g., "+3;Key Title;" Note that the last
     semi-colon is required and will generate an error if it is left
     out.

     Here are some plot examples:

          plot (x, y, "@12", x, y2, x, y3, "4", x, y4, "+")

     This command will plot `y' with points of type 2 (displayed as
     `+') and color 1 (red), `y2' with lines, `y3' with lines of color
     4 (magenta) and `y4' with points displayed as `+'.

          plot (b, "*", "markersize", 3)

     This command will plot the data in the variable `b', with points
     displayed as `*' with a marker size of 3.

          t = 0:0.1:6.3;
          plot (t, cos(t), "-;cos(t);", t, sin(t), "+3;sin(t);");

     This will plot the cosine and sine functions and label them
     accordingly in the key.

     If the first argument is an axis handle, then plot into these axes,
     rather than the current axis handle returned by `gca'.

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

     *See also:* *note semilogx: doc-semilogx, *note semilogy:
     doc-semilogy, *note loglog: doc-loglog, *note polar: doc-polar,
     *note mesh: doc-mesh, *note contour: doc-contour, *note bar:
     doc-bar, *note stairs: doc-stairs, *note errorbar: doc-errorbar,
     *note xlabel: doc-xlabel, *note ylabel: doc-ylabel, *note title:
     doc-title, *note print: doc-print.

   The `plotyy' function may be used to create a plot with two
independent y axes.

 -- Function File:  plotyy (X1, Y1, X2, Y2)
 -- Function File:  plotyy (..., FUN)
 -- Function File:  plotyy (..., FUN1, FUN2)
 -- Function File:  plotyy (H, ...)
 -- Function File: [AX, H1, H2] = plotyy (...)
     Plot two sets of data with independent y-axes.  The arguments X1
     and Y1 define the arguments for the first plot and X1 and Y2 for
     the second.

     By default the arguments are evaluated with `feval (@plot, X, Y)'.
     However the type of plot can be modified with the FUN argument, in
     which case the plots are generated by `feval (FUN, X, Y)'.  FUN
     can be a function handle, an inline function or a string of a
     function name.

     The function to use for each of the plots can be independently
     defined with FUN1 and FUN2.

     If given, H defines the principal axis in which to plot the X1 and
     Y1 data.  The return value AX is a two element vector with the
     axis handles of the two plots.  H1 and H2 are handles to the
     objects generated by the plot commands.

          x = 0:0.1:2*pi;
          y1 = sin (x);
          y2 = exp (x - 1);
          ax = plotyy (x, y1, x - 1, y2, @plot, @semilogy);
          xlabel ("X");
          ylabel (ax(1), "Axis 1");
          ylabel (ax(2), "Axis 2");

   The functions `semilogx', `semilogy', and `loglog' are similar to
the `plot' function, but produce plots in which one or both of the axes
use log scales.

 -- Function File:  semilogx (Y)
 -- Function File:  semilogx (X, Y)
 -- Function File:  semilogx (X, Y, PROPERTY, VALUE, ...)
 -- Function File:  semilogx (X, Y, FMT)
 -- Function File:  semilogx (H, ...)
 -- Function File: H = semilogx (...)
     Produce a two-dimensional plot using a logarithmic scale for the X
     axis.  See the documentation of `plot' for a description of the
     arguments that `semilogx' will accept.

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

     *See also:* *note plot: doc-plot, *note semilogy: doc-semilogy,
     *note loglog: doc-loglog.

 -- Function File:  semilogy (Y)
 -- Function File:  semilogy (X, Y)
 -- Function File:  semilogy (X, Y, PROPERTY, VALUE, ...)
 -- Function File:  semilogy (X, Y, FMT)
 -- Function File:  semilogy (H, ...)
 -- Function File: H = semilogy (...)
     Produce a two-dimensional plot using a logarithmic scale for the Y
     axis.  See the documentation of `plot' for a description of the
     arguments that `semilogy' will accept.

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

     *See also:* *note plot: doc-plot, *note semilogx: doc-semilogx,
     *note loglog: doc-loglog.

 -- Function File:  loglog (Y)
 -- Function File:  loglog (X, Y)
 -- Function File:  loglog (X, Y, PROPERTY, VALUE, ...)
 -- Function File:  loglog (X, Y, FMT)
 -- Function File:  loglog (H, ...)
 -- Function File: H = loglog (...)
     Produce a two-dimensional plot using log scales for both axes.  See
     the documentation of `plot' for a description of the arguments
     that `loglog' will accept.

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

     *See also:* *note plot: doc-plot, *note semilogx: doc-semilogx,
     *note semilogy: doc-semilogy.

   The functions `bar', `barh', `stairs', and `stem' are useful for
displaying discrete data.  For example,

     hist (randn (10000, 1), 30);

produces the histogram of 10,000 normally distributed random numbers
shown in *note fig:hist::.


+---------------------------------+
| Image unavailable in text mode. |
+---------------------------------+
Figure 15.2: Histogram.

 -- Function File:  bar (X, Y)
 -- Function File:  bar (Y)
 -- Function File:  bar (X, Y, W)
 -- Function File:  bar (X, Y, W, STYLE)
 -- Function File: H = bar (..., PROP, VAL)
 -- Function File:  bar (H, ...)
     Produce a bar graph from two vectors of x-y data.

     If only one argument is given, Y, it is taken as a vector of
     y-values and the x coordinates are taken to be the indices of the
     elements.

     The default width of 0.8 for the bars can be changed using W.

     If Y is a matrix, then each column of Y is taken to be a separate
     bar graph plotted on the same graph.  By default the columns are
     plotted side-by-side.  This behavior can be changed by the STYLE
     argument, which can take the values `"grouped"' (the default), or
     `"stacked"'.

     The optional return value H is a handle to the created "bar series"
     object with one handle per column of the variable Y.  This series
     allows common elements of the group of bar series objects to be
     changed in a single bar series and the same properties are changed
     in the other "bar series".  For example,

          h = bar (rand (5, 10));
          set (h(1), "basevalue", 0.5);

     changes the position on the base of all of the bar series.

     The optional input handle H allows an axis handle to be passed.

     The bar graph's appearance may be modified by specifying
     property/value pairs.  The following example modifies the face and
     edge colors.

          bar (randn (1, 100), "facecolor", "r", "edgecolor", "b")

     The color of the bars is taken from the figure's colormap, such
     that

          bar (rand (10, 3));
          colormap (summer (64));

     will change the colors used for the bars.  The color of bars can
     also be set manually using the "facecolor" property as shown below.

          h = bar (rand (10, 3));
          set (h(1), "facecolor", "r")
          set (h(2), "facecolor", "g")
          set (h(3), "facecolor", "b")

     *See also:* *note barh: doc-barh, *note plot: doc-plot.

 -- Function File:  barh (X, Y)
 -- Function File:  barh (Y)
 -- Function File:  barh (X, Y, W)
 -- Function File:  barh (X, Y, W, STYLE)
 -- Function File: H = barh (..., PROP, VAL)
 -- Function File:  barh (H, ...)
     Produce a horizontal bar graph from two vectors of x-y data.

     If only one argument is given, it is taken as a vector of y-values
     and the x coordinates are taken to be the indices of the elements.

     The default width of 0.8 for the bars can be changed using W.

     If Y is a matrix, then each column of Y is taken to be a separate
     bar graph plotted on the same graph.  By default the columns are
     plotted side-by-side.  This behavior can be changed by the STYLE
     argument, which can take the values `"grouped"' (the default), or
     `"stacked"'.

     The optional input handle H allows an axis handle to be passed.
     Properties of the patch graphics object can be changed using PROP,
     VAL pairs.

     The optional return value H is a graphics handle to the created
     bar series object.  See `bar' for a description of the use of the
     bar series.

     *See also:* *note bar: doc-bar, *note plot: doc-plot.

 -- Function File:  hist (Y)
 -- Function File:  hist (Y, X)
 -- Function File:  hist (Y, NBINS)
 -- Function File:  hist (Y, X, NORM)
 -- Function File: [NN, XX] = hist (...)
 -- Function File: [...] = hist (..., PROP, VAL)
     Produce histogram counts or plots.

     With one vector input argument, Y, plot a histogram of the values
     with 10 bins.  The range of the histogram bins is determined by the
     range of the data.  With one matrix input argument, Y, plot a
     histogram where each bin contains a bar per input column.

     Given a second vector argument, X, use that as the centers of the
     bins, with the width of the bins determined from the adjacent
     values in the vector.

     If scalar, the second argument, NBINS, defines the number of bins.

     If a third argument is provided, the histogram is normalized such
     that the sum of the bars is equal to NORM.

     Extreme values are lumped in the first and last bins.

     With two output arguments, produce the values NN and XX such that
     `bar (XX, NN)' will plot the histogram.

     The histogram's appearance may be modified by specifying
     property/value pairs, PROP and VAL pairs.  For example the face
     and edge color may be modified.

          hist (randn (1, 100), 25, "facecolor", "r", "edgecolor", "b");

     The histograms colors also depend upon the colormap.

          hist (rand (10, 3));
          colormap (summer ());

     *See also:* *note bar: doc-bar.

 -- Function File:  stairs (Y)
 -- Function File:  stairs (X, Y)
 -- Function File:  stairs (..., STYLE)
 -- Function File:  stairs (..., PROP, VAL)
 -- Function File:  stairs (H, ...)
 -- Function File: H = stairs (...)
 -- Function File: [XSTEP, YSTEP] = stairs (...)
     Produce a stairstep plot.  The arguments may be vectors or
     matrices.

     If only one argument is given, it is taken as a vector of y-values
     and the x coordinates are taken to be the indices of the elements.

     If one output argument is requested, return a graphics handle to
     the plot.  If two output arguments are specified, the data are
     generated but not plotted.  For example,

          stairs (x, y);

     and

          [xs, ys] = stairs (x, y);
          plot (xs, ys);

     are equivalent.

     *See also:* *note plot: doc-plot, *note semilogx: doc-semilogx,
     *note semilogy: doc-semilogy, *note loglog: doc-loglog, *note
     polar: doc-polar, *note mesh: doc-mesh, *note contour:
     doc-contour, *note bar: doc-bar, *note xlabel: doc-xlabel, *note
     ylabel: doc-ylabel, *note title: doc-title.

 -- Function File:  stem (X)
 -- Function File:  stem (X, Y)
 -- Function File:  stem (X, Y, LINESPEC)
 -- Function File:  stem (..., "filled")
 -- Function File: H = stem (...)
     Plot a stem graph from two vectors of x-y data.  If only one
     argument is given, it is taken as the y-values and the x
     coordinates are taken from the indices of the elements.

     If Y is a matrix, then each column of the matrix is plotted as a
     separate stem graph.  In this case X can either be a vector, the
     same length as the number of rows in Y, or it can be a matrix of
     the same size as Y.

     The default color is `"b"' (blue).  The default line style is
     `"-"' and the default marker is `"o"'.  The line style can be
     altered by the `linespec' argument in the same manner as the
     `plot' command.  For example,

          x = 1:10;
          y = 2*x;
          stem (x, y, "r");

     plots 10 stems with heights from 2 to 20 in red;

     The optional return value H is a vector of "stem series" graphics
     handles with one handle per column of the variable Y.  The handle
     regroups the elements of the stem graph together as the children
     of the "stem series" handle, allowing them to be altered together.
     For example,

          x = [0:10]';
          y = [sin(x), cos(x)]
          h = stem (x, y);
          set (h(2), "color", "g");
          set (h(1), "basevalue", -1)

     changes the color of the second "stem series" and moves the base
     line of the first.

     *See also:* *note bar: doc-bar, *note barh: doc-barh, *note plot:
     doc-plot.

 -- Function File: H = stem3 (X, Y, Z, LINESPEC)
     Plot a three-dimensional stem graph and return the handles of the
     line and marker objects used to draw the stems as "stem series"
     object.  The default color is `"r"' (red).  The default line style
     is `"-"' and the default marker is `"o"'.

     For example,

          theta = 0:0.2:6;
          stem3 (cos (theta), sin (theta), theta)

     plots 31 stems with heights from 0 to 6 lying on a circle.  Color
     definitions with RGB-triples are not valid!

     *See also:* *note bar: doc-bar, *note barh: doc-barh, *note stem:
     doc-stem, *note plot: doc-plot.

 -- Function File:  scatter (X, Y)
 -- Function File:  scatter (X, Y, S)
 -- Function File:  scatter (X, Y, C)
 -- Function File:  scatter (X, Y, S, C)
 -- Function File:  scatter (X, Y, S, C, STYLE)
 -- Function File:  scatter (X, Y, S, C, PROP, VAL)
 -- Function File:  scatter (..., "filled")
 -- Function File:  scatter (H, ...)
 -- Function File: H = scatter (...)
     Plot a scatter plot of the data.  A marker is plotted at each point
     defined by the points in the vectors X and Y.  The size of the
     markers used is determined by the S, which can be a scalar, a
     vector of the same length of X and Y.  If S is not given or is an
     empty matrix, then the default value of 8 points is used.

     The color of the markers is determined by C, which can be a string
     defining a fixed color; a 3-element vector giving the red,
     green,and blue components of the color; a vector of the same
     length as X that gives a scaled index into the current colormap;
     or a N-by-3 matrix defining the colors of each of the markers
     individually.

     The marker to use can be changed with the STYLE argument, that is a
     string defining a marker in the same manner as the `plot' command.
     If the argument `"filled"' is given then the markers as filled.
     All additional arguments are passed to the underlying patch
     command.

     The optional return value H provides a handle to the patch object

          x = randn (100, 1);
          y = randn (100, 1);
          scatter (x, y, [], sqrt(x.^2 + y.^2));

     *See also:* *note plot: doc-plot, *note patch: doc-patch, *note
     scatter3: doc-scatter3.

 -- Function File:  plotmatrix (X, Y)
 -- Function File:  plotmatrix (X)
 -- Function File:  plotmatrix (..., STYLE)
 -- Function File:  plotmatrix (H, ...)
 -- Function File: [H, AX, BIGAX, P, PAX] = plotmatrix (...)
     Scatter plot of the columns of one matrix against another.  Given
     the arguments X and Y, that have a matching number of rows,
     `plotmatrix' plots a set of axes corresponding to

          plot (X (:, i), Y (:, j)

     Given a single argument X, then this is equivalent to

          plotmatrix (X, X)

     except that the diagonal of the set of axes will be replaced with
     the histogram `hist (X (:, i))'.

     The marker to use can be changed with the STYLE argument, that is a
     string defining a marker in the same manner as the `plot' command.
     If a leading axes handle H is passed to `plotmatrix', then this
     axis will be used for the plot.

     The optional return value H provides handles to the individual
     graphics objects in the scatter plots, whereas AX returns the
     handles to the scatter plot axis objects.  BIGAX is a hidden axis
     object that surrounds the other axes, such that the commands
     `xlabel', `title', etc., will be associated with this hidden axis.
     Finally P returns the graphics objects associated with the
     histogram and PAX the corresponding axes objects.

          plotmatrix (randn (100, 3), "g+")


 -- Function File:  pareto (X)
 -- Function File:  pareto (X, Y)
 -- Function File:  pareto (H, ...)
 -- Function File: H = pareto (...)
     Draw a Pareto chart, also called ABC chart.  A Pareto chart is a
     bar graph used to arrange information in such a way that
     priorities for process improvement can be established.  It
     organizes and displays information to show the relative importance
     of data.  The chart is similar to the histogram or bar chart,
     except that the bars are arranged in decreasing order from left to
     right along the abscissa.

     The fundamental idea (Pareto principle) behind the use of Pareto
     diagrams is that the majority of an effect is due to a small
     subset of the causes, so for quality improvement the first few (as
     presented on the diagram) contributing causes to a problem usually
     account for the majority of the result.  Thus, targeting these
     "major causes" for elimination results in the most cost-effective
     improvement scheme.

     The data are passed as X and the abscissa as Y.  If Y is absent,
     then the abscissa are assumed to be `1 : length (X)'.  Y can be a
     string array, a cell array of strings or a numerical vector.

     The optional return value H is a 2-element vector with a graphics
     handle for the created bar plot and a second handle for the
     created line plot.

     An example of the use of `pareto' is

          Cheese = {"Cheddar", "Swiss", "Camembert", ...
                    "Munster", "Stilton", "Blue"};
          Sold = [105, 30, 70, 10, 15, 20];
          pareto (Sold, Cheese);

 -- Function File:  rose (TH, R)
 -- Function File:  rose (H, ...)
 -- Function File: H = rose (...)
 -- Function File: [R, TH] = rose (...)
     Plot an angular histogram.  With one vector argument TH, plots the
     histogram with 20 angular bins.  If TH is a matrix, then each
     column of TH produces a separate histogram.

     If R is given and is a scalar, then the histogram is produced with
     R bins.  If R is a vector, then the center of each bin are defined
     by the values of R.

     The optional return value H is a vector of graphics handles to the
     line objects representing each histogram.

     If two output arguments are requested then, rather than plotting
     the histogram, the polar vectors necessary to plot the histogram
     are returned.

          [r, t] = rose ([2*randn(1e5,1), pi + 2*randn(1e5,1)]);
          polar (r, t);

     *See also:* *note polar: doc-polar, *note compass: doc-compass,
     *note hist: doc-hist.

   The `contour', `contourf' and `contourc' functions produce
two-dimensional contour plots from three-dimensional data.

 -- Function File:  contour (Z)
 -- Function File:  contour (Z, VN)
 -- Function File:  contour (X, Y, Z)
 -- Function File:  contour (X, Y, Z, VN)
 -- Function File:  contour (..., STYLE)
 -- Function File:  contour (H, ...)
 -- Function File: [C, H] = contour (...)
     Plot level curves (contour lines) of the matrix Z, using the
     contour matrix C computed by `contourc' from the same arguments;
     see the latter for their interpretation.  The set of contour
     levels, C, is only returned if requested.  For example:

          x = 0:2;
          y = x;
          z = x' * y;
          contour (x, y, z, 2:3)

     The style to use for the plot can be defined with a line style
     STYLE in a similar manner to the line styles used with the `plot'
     command.  Any markers defined by STYLE are ignored.

     The optional input and output argument H allows an axis handle to
     be passed to `contour' and the handles to the contour objects to be
     returned.

     *See also:* *note contourc: doc-contourc, *note patch: doc-patch,
     *note plot: doc-plot.

 -- Function File: [C, H] = contourf (X, Y, Z, LVL)
 -- Function File: [C, H] = contourf (X, Y, Z, N)
 -- Function File: [C, H] = contourf (X, Y, Z)
 -- Function File: [C, H] = contourf (Z, N)
 -- Function File: [C, H] = contourf (Z, LVL)
 -- Function File: [C, H] = contourf (Z)
 -- Function File: [C, H] = contourf (AX, ...)
 -- Function File: [C, H] = contourf (..., "PROPERTY", VAL)
     Compute and plot filled contours of the matrix Z.  Parameters X, Y
     and N or LVL are optional.

     The return value C is a 2xn matrix containing the contour lines as
     described in the help to the contourc function.

     The return value H is handle-vector to the patch objects creating
     the filled contours.

     If X and Y are omitted they are taken as the row/column index of
     Z.  N is a scalar denoting the number of lines to compute.
     Alternatively LVL is a vector containing the contour levels.  If
     only one value (e.g., lvl0) is wanted, set LVL to [lvl0, lvl0].
     If both N or LVL are omitted a default value of 10 contour level
     is assumed.

     If provided, the filled contours are added to the axes object AX
     instead of the current axis.

     The following example plots filled contours of the `peaks'
     function.

          [x, y, z] = peaks (50);
          contourf (x, y, z, -7:9)

     *See also:* *note contour: doc-contour, *note contourc:
     doc-contourc, *note patch: doc-patch.

 -- Function File: [C, LEV] = contourc (X, Y, Z, VN)
     Compute isolines (contour lines) of the matrix Z.  Parameters X, Y
     and VN are optional.

     The return value LEV is a vector of the contour levels.  The
     return value C is a 2 by N matrix containing the contour lines in
     the following format

          C = [lev1, x1, x2, ..., levn, x1, x2, ...
               len1, y1, y2, ..., lenn, y1, y2, ...]

     in which contour line N has a level (height) of LEVN and length of
     LENN.

     If X and Y are omitted they are taken as the row/column index of
     Z.  VN is either a scalar denoting the number of lines to compute
     or a vector containing the values of the lines.  If only one value
     is wanted, set `VN = [val, val]'; If VN is omitted it defaults to
     10.

     For example:

          x = 0:2;
          y = x;
          z = x' * y;
          contourc (x, y, z, 2:3)
             =>   2.0000   2.0000   1.0000   3.0000   1.5000   2.0000
                  2.0000   1.0000   2.0000   2.0000   2.0000   1.5000

     *See also:* *note contour: doc-contour.

 -- Function File:  contour3 (Z)
 -- Function File:  contour3 (Z, VN)
 -- Function File:  contour3 (X, Y, Z)
 -- Function File:  contour3 (X, Y, Z, VN)
 -- Function File:  contour3 (..., STYLE)
 -- Function File:  contour3 (H, ...)
 -- Function File: [C, H] = contour3 (...)
     Plot level curves (contour lines) of the matrix Z, using the
     contour matrix C computed by `contourc' from the same arguments;
     see the latter for their interpretation.  The contours are plotted
     at the Z level corresponding to their contour.  The set of contour
     levels, C, is only returned if requested.  For example:

          contour3 (peaks (19));
          hold on
          surface (peaks (19), "facecolor", "none", "EdgeColor", "black");
          colormap hot;

     The style to use for the plot can be defined with a line style
     STYLE in a similar manner to the line styles used with the `plot'
     command.  Any markers defined by STYLE are ignored.

     The optional input and output argument H allows an axis handle to
     be passed to `contour' and the handles to the contour objects to be
     returned.

     *See also:* *note contourc: doc-contourc, *note patch: doc-patch,
     *note plot: doc-plot.

   The `errorbar', `semilogxerr', `semilogyerr', and `loglogerr'
functions produce plots with error bar markers.  For example,

     x = 0:0.1:10;
     y = sin (x);
     yp =  0.1 .* randn (size (x));
     ym = -0.1 .* randn (size (x));
     errorbar (x, sin (x), ym, yp);

produces the figure shown in *note fig:errorbar::.


+---------------------------------+
| Image unavailable in text mode. |
+---------------------------------+
Figure 15.3: Errorbar plot.

 -- Function File:  errorbar (ARGS)
     This function produces two-dimensional plots with errorbars.  Many
     different combinations of arguments are possible.  The simplest
     form is

          errorbar (Y, EY)

     where the first argument is taken as the set of Y coordinates and
     the second argument EY is taken as the errors of the Y values.  X
     coordinates are taken to be the indices of the elements, starting
     with 1.

     If more than two arguments are given, they are interpreted as

          errorbar (X, Y, ..., FMT, ...)

     where after X and Y there can be up to four error parameters such
     as EY, EX, LY, UY, etc., depending on the plot type.  Any number
     of argument sets may appear, as long as they are separated with a
     format string FMT.

     If Y is a matrix, X and error parameters must also be matrices
     having same dimensions.  The columns of Y are plotted versus the
     corresponding columns of X and errorbars are drawn from the
     corresponding columns of error parameters.

     If FMT is missing, yerrorbars ("~") plot style is assumed.

     If the FMT argument is supplied, it is interpreted as in normal
     plots.  In addition, FMT may include an errorbar style which must
     precede the line and marker format.  The following plot styles are
     supported by errorbar:

    `~'
          Set yerrorbars plot style (default).

    `>'
          Set xerrorbars plot style.

    `~>'
          Set xyerrorbars plot style.

    `#'
          Set boxes plot style.

    `#~'
          Set boxerrorbars plot style.

    `#~>'
          Set boxxyerrorbars plot style.

     Examples:

          errorbar (X, Y, EX, ">")

     produces an xerrorbar plot of Y versus X with X errorbars drawn
     from X-EX to X+EX.

          errorbar (X, Y1, EY, "~",
                    X, Y2, LY, UY)

     produces yerrorbar plots with Y1 and Y2 versus X.  Errorbars for
     Y1 are drawn from Y1-EY to Y1+EY, errorbars for Y2 from Y2-LY to
     Y2+UY.

          errorbar (X, Y, LX, UX,
                    LY, UY, "~>")

     produces an xyerrorbar plot of Y versus X in which X errorbars are
     drawn from X-LX to X+UX and Y errorbars from Y-LY to Y+UY.

     *See also:* *note semilogxerr: doc-semilogxerr, *note semilogyerr:
     doc-semilogyerr, *note loglogerr: doc-loglogerr.

 -- Function File:  semilogxerr (ARGS)
     Produce two-dimensional plots using a logarithmic scale for the X
     axis and errorbars at each data point.  Many different
     combinations of arguments are possible.  The most used form is

          semilogxerr (X, Y, EY, FMT)

     which produces a semi-logarithmic plot of Y versus X with errors
     in the Y-scale defined by EY and the plot format defined by FMT.
     See `errorbar' for available formats and additional information.

     *See also:* *note errorbar: doc-errorbar, *note loglogerr:
     doc-loglogerr, *note semilogyerr: doc-semilogyerr.

 -- Function File:  semilogyerr (ARGS)
     Produce two-dimensional plots using a logarithmic scale for the Y
     axis and errorbars at each data point.  Many different
     combinations of arguments are possible.  The most used form is

          semilogyerr (X, Y, EY, FMT)

     which produces a semi-logarithmic plot of Y versus X with errors
     in the Y-scale defined by EY and the plot format defined by FMT.
     See `errorbar' for available formats and additional information.

     *See also:* *note errorbar: doc-errorbar, *note loglogerr:
     doc-loglogerr, *note semilogxerr: doc-semilogxerr.

 -- Function File:  loglogerr (ARGS)
     Produce two-dimensional plots on double logarithm axis with
     errorbars.  Many different combinations of arguments are possible.
     The most used form is

          loglogerr (X, Y, EY, FMT)

     which produces a double logarithm plot of Y versus X with errors
     in the Y-scale defined by EY and the plot format defined by FMT.
     See errorbar for available formats and additional information.

     *See also:* *note errorbar: doc-errorbar, *note semilogxerr:
     doc-semilogxerr, *note semilogyerr: doc-semilogyerr.

   Finally, the `polar' function allows you to easily plot data in
polar coordinates.  However, the display coordinates remain rectangular
and linear.  For example,

     polar (0:0.1:10*pi, 0:0.1:10*pi);

produces the spiral plot shown in *note fig:polar::.


+---------------------------------+
| Image unavailable in text mode. |
+---------------------------------+
Figure 15.4: Polar plot.

 -- Function File:  polar (THETA, RHO)
 -- Function File:  polar (THETA, RHO, FMT)
 -- Function File:  polar (H, ...)
 -- Function File: H = polar (...)
     Create a two-dimensional plot from polar coordinates THETA and RHO.

     The optional argument FMT specifies the line format.

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

     *See also:* *note plot: doc-plot.

 -- Function File:  pie (X)
 -- Function File:  pie (X, EXPLODE)
 -- Function File:  pie (..., LABELS)
 -- Function File:  pie (H, ...);
 -- Function File: H = pie (...);
     Produce a 2-D pie chart.

     Called with a single vector argument, produces a pie chart of the
     elements in X, with the size of the slice determined by percentage
     size of the values of X.

     The variable EXPLODE is a vector of the same length as X that if
     non zero 'explodes' the slice from the pie chart.

     If given LABELS is a cell array of strings of the same length as
     X, giving the labels of each of the slices of the pie chart.

     The optional return value H is a list of handles to the patch and
     text objects generating the plot.

     *See also:* *note pie3: doc-pie3, *note bar: doc-bar, *note stem:
     doc-stem.

 -- Function File:  pie3 (X)
 -- Function File:  pie3 (X, EXPLODE)
 -- Function File:  pie3 (..., LABELS)
 -- Function File:  pie3 (H, ...);
 -- Function File: H = pie3 (...);
     Draw a 3-D pie chart.

     Called with a single vector argument, produces a 3-D pie chart of
     the elements in X, with the size of the slice determined by
     percentage size of the values of X.

     The variable EXPLODE is a vector of the same length as X that if
     non zero 'explodes' the slice from the pie chart.

     If given LABELS is a cell array of strings of the same length as
     X, giving the labels of each of the slices of the pie chart.

     The optional return value H is a list of graphics handles to the
     patch, surface, and text objects generating the plot.

     *See also:* *note pie: doc-pie, *note bar: doc-bar, *note stem:
     doc-stem.

 -- Function File:  quiver (U, V)
 -- Function File:  quiver (X, Y, U, V)
 -- Function File:  quiver (..., S)
 -- Function File:  quiver (..., STYLE)
 -- Function File:  quiver (..., 'filled')
 -- Function File:  quiver (H, ...)
 -- Function File: H = quiver (...)
     Plot the `(U, V)' components of a vector field in an `(X, Y)'
     meshgrid.  If the grid is uniform, you can specify X and Y as
     vectors.

     If X and Y are undefined they are assumed to be `(1:M, 1:N)' where
     `[M, N] = size(U)'.

     The variable S is a scalar defining a scaling factor to use for
     the arrows of the field relative to the mesh spacing.  A value of 0
     disables all scaling.  The default value is 1.

     The style to use for the plot can be defined with a line style
     STYLE in a similar manner to the line styles used with the `plot'
     command.  If a marker is specified then markers at the grid points
     of the vectors are printed rather than arrows.  If the argument
     'filled' is given then the markers as filled.

     The optional return value H is a graphics handle to a quiver
     object.  A quiver object regroups the components of the quiver
     plot (body, arrow, and marker), and allows them to be changed
     together.

          [x, y] = meshgrid (1:2:20);
          h = quiver (x, y, sin (2*pi*x/10), sin (2*pi*y/10));
          set (h, "maxheadsize", 0.33);

     *See also:* *note plot: doc-plot.

 -- Function File:  quiver3 (U, V, W)
 -- Function File:  quiver3 (X, Y, Z, U, V, W)
 -- Function File:  quiver3 (..., S)
 -- Function File:  quiver3 (..., STYLE)
 -- Function File:  quiver3 (..., 'filled')
 -- Function File:  quiver3 (H, ...)
 -- Function File: H = quiver3 (...)
     Plot the `(U, V, W)' components of a vector field in an `(X, Y),
     Z' meshgrid.  If the grid is uniform, you can specify X, Y Z as
     vectors.

     If X, Y and Z are undefined they are assumed to be `(1:M, 1:N,
     1:P)' where `[M, N] = size(U)' and `P = max (size (W))'.

     The variable S is a scalar defining a scaling factor to use for
     the arrows of the field relative to the mesh spacing.  A value of 0
     disables all scaling.  The default value is 1.

     The style to use for the plot can be defined with a line style
     STYLE in a similar manner to the line styles used with the `plot'
     command.  If a marker is specified then markers at the grid points
     of the vectors are printed rather than arrows.  If the argument
     'filled' is given then the markers as filled.

     The optional return value H is a graphics handle to a quiver
     object.  A quiver object regroups the components of the quiver
     plot (body, arrow, and marker), and allows them to be changed
     together.

          [x, y, z] = peaks (25);
          surf (x, y, z);
          hold on;
          [u, v, w] = surfnorm (x, y, z / 10);
          h = quiver3 (x, y, z, u, v, w);
          set (h, "maxheadsize", 0.33);

     *See also:* *note plot: doc-plot.

 -- Function File:  compass (U, V)
 -- Function File:  compass (Z)
 -- Function File:  compass (..., STYLE)
 -- Function File:  compass (H, ...)
 -- Function File: H = compass (...)
     Plot the `(U, V)' components of a vector field emanating from the
     origin of a polar plot.  If a single complex argument Z is given,
     then `U = real (Z)' and `V = imag (Z)'.

     The style to use for the plot can be defined with a line style
     STYLE in a similar manner to the line styles used with the `plot'
     command.

     The optional return value H is a vector of graphics handles to the
     line objects representing the drawn vectors.

          a = toeplitz ([1;randn(9,1)], [1,randn(1,9)]);
          compass (eig (a));

     *See also:* *note polar: doc-polar, *note quiver: doc-quiver,
     *note feather: doc-feather, *note plot: doc-plot.

 -- Function File:  feather (U, V)
 -- Function File:  feather (Z)
 -- Function File:  feather (..., STYLE)
 -- Function File:  feather (H, ...)
 -- Function File: H = feather (...)
     Plot the `(U, V)' components of a vector field emanating from
     equidistant points on the x-axis.  If a single complex argument Z
     is given, then `U = real (Z)' and `V = imag (Z)'.

     The style to use for the plot can be defined with a line style
     STYLE in a similar manner to the line styles used with the `plot'
     command.

     The optional return value H is a vector of graphics handles to the
     line objects representing the drawn vectors.

          phi = [0 : 15 : 360] * pi/180;
          feather (sin (phi), cos (phi));

     *See also:* *note plot: doc-plot, *note quiver: doc-quiver, *note
     compass: doc-compass.

 -- Function File:  pcolor (X, Y, C)
 -- Function File:  pcolor (C)
     Density plot for given matrices X, and Y from `meshgrid' and a
     matrix C corresponding to the X and Y coordinates of the mesh's
     vertices.  If X and Y are vectors, then a typical vertex is (X(j),
     Y(i), C(i,j)).  Thus, columns of C correspond to different X
     values and rows of C correspond to different Y values.

     The `colormap' is scaled to the extents of C.  Limits may be
     placed on the color axis by the command `caxis', or by setting the
     `clim' property of the parent axis.

     The face color of each cell of the mesh is determined by
     interpolating the values of C for the cell's vertices.  Contrast
     this with `imagesc' which renders one cell for each element of C.

     `shading' modifies an attribute determining the manner by which the
     face color of each cell is interpolated from the values of C, and
     the visibility of the cells' edges.  By default the attribute is
     "faceted", which renders a single color for each cell's face with
     the edge visible.

     H is the handle to the surface object.

     *See also:* *note caxis: doc-caxis, *note contour: doc-contour,
     *note meshgrid: doc-meshgrid, *note imagesc: doc-imagesc, *note
     shading: doc-shading.

 -- Function File:  area (X, Y)
 -- Function File:  area (X, Y, LVL)
 -- Function File:  area (..., PROP, VAL, ...)
 -- Function File:  area (Y, ...)
 -- Function File:  area (H, ...)
 -- Function File: H = area (...)
     Area plot of cumulative sum of the columns of Y.  This shows the
     contributions of a value to a sum, and is functionally similar to
     `plot (X, cumsum (Y, 2))', except that the area under the curve is
     shaded.

     If the X argument is omitted it is assumed to be given by `1 :
     rows (Y)'.  A value LVL can be defined that determines where the
     base level of the shading under the curve should be defined.

     Additional arguments to the `area' function are passed to `patch'.

     The optional return value H is a graphics handle to the hggroup
     object representing the area patch objects.

     *See also:* *note plot: doc-plot, *note patch: doc-patch.

 -- Function File:  comet (Y)
 -- Function File:  comet (X, Y)
 -- Function File:  comet (X, Y, P)
 -- Function File:  comet (AX, ...)
     Produce a simple comet style animation along the trajectory
     provided by the input coordinate vectors (X, Y), where X will
     default to the indices of Y.

     The speed of the comet may be controlled by P, which represents the
     time which passes as the animation passes from one point to the
     next.  The default for P is 0.1 seconds.

     If AX is specified the animation is produced in that axis rather
     than the `gca'.

 -- Function File:  comet3 (Z)
 -- Function File:  comet3 (X, Y, Z, P)
 -- Function File:  comet3 (AX, ...)
     Produce a simple comet style animation along the trajectory
     provided by the input coordinate vectors (X, Y), where X will
     default to the indices of Y.

     The speed of the comet may be controlled by P, which represents the
     time which passes as the animation passes from one point to the
     next.  The default for P is 0.1 seconds.

     If AX is specified the animation is produced in that axis rather
     than the `gca'.

