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: 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 and exponentiation
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 increasing
precedence.

`statement separators'
     `;', `,'.

`assignment'
     `=', `+=', `-=', `*=',`/='.  This operator groups right to left.

`logical "or" and "and"'
     `||', `&&'.

`element-wise "or" and "and"'
     `|', `&'.

`relational'
     `<', `<=', `==', `>=', `>', `!=', `~='.

`colon'
     `:'.

`add, subtract'
     `+', `-'.

`multiply, divide'
     `*', `/', `\', `.\', `.*', `./'.

`transpose'
     `'', `.''

`unary plus, minus, increment, decrement, and ``not'''
     `+', `-', `++', `--', `!', `~'.

`exponentiation'
     `^', `**', `.^', `.**'.


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

* 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' is necessary in order to be able to write
     functions that call user-supplied functions, because Octave does
     not have a way to declare a pointer to a function (like C) or to
     declare a special kind of variable that can be used to hold the
     name of a function (like `EXTERNAL' in Fortran).  Instead, you
     must refer to functions by name, and use `feval' to call them.

   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, CATCH)
     Like `eval', except that the expressions are evaluated in the
     context CONTEXT, which may be either `"caller"' or `"base"'.

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


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]; b = 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 varargout: doc-varargout.

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


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.

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

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

 -- Function File: MSGSTR = nargoutchk (MINARGS, MAXARGS, NARGS)
 -- Function File: MSGSTR = nargoutchk (MINARGS, MAXARGS, NARGS,
          "string")
 -- Function File: MSGSTRUCT = nargoutchk (MINARGS, MAXARGS, NARGS,
          "struct")
     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 error: doc-error,
     *note nargout: doc-nargout, *note nargin: doc-nargin.

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


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


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

         `"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 "async" to start the editor in async mode.
          The default is "sync" (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 it's 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, "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 the directory names that match.


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 (FCN)
     Unlock the named function.  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 (FCN)
     Return true if the named function 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:  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.

 -- Built-in Function:  vectorize (FUN)
     Create a vectorized version of the inline function FUN by
     replacing all occurrences of `*', `/', etc., with `.*', `./', etc.

 -- Function File:  symvar (S)
     Identifies 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.

`control'
     Functions for design and simulation of automatic control systems.

`elfun'
     Elementary functions.

`finance'
     Functions for computing interest payments, investment values, and
     rates of return.

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

`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'
     Minimization of functions.

`path'
     Functions to manage the directory path Octave uses to find
     functions.

`pkg'
     Install external packages of functions in Octave.

`plot'
     Functions for displaying and printing two- and three-dimensional
     graphs.

`polynomial'
     Functions for manipulating polynomials.

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

`special-matrix'
     Functions that create special matrix forms.

`startup'
     Octave's system-wide startup file.

`statistics'
     Statistical functions.

`strings'
     Miscellaneous string-handling functions.

`testfun'
     Perform unit tests on other functions.

`time'
     Functions related to time keeping.


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


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)
     Query or set the internal variable that controls whether Octave
     will try to ring the terminal bell before printing an error
     message.


File: octave.info,  Node: Catching 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.  Called without any arguments
     returns a structure containing the last error message, as well as
     other information related to this error.  The elements of this
     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 might be an empty structure if this in the
          case where this information cannot be obtained.  The fields
          of this 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 ERR structure may also be passed to `lasterror' to set the
     information about the last error.  The only constraint on ERR in
     that case is that it is a scalar structure.  Any fields of ERR
     that match the above are set to the value passed in ERR, while
     other fields are set to their default values.

     If `lasterror' is called with the argument 'reset', all values take
     their default values.

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

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

 -- Built-in Function:  warning ("on", ID)
 -- Built-in Function:  warning ("off", ID)
 -- Built-in Function:  warning ("error", ID)
 -- Built-in Function:  warning ("query", ID)
     Set or query the state of a particular warning using the identifier
     ID.  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.

     *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: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: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:empty-list-elements'
     If the `Octave:empty-list-elements' warning is enabled, a warning
     is issued when an empty matrix is found in a matrix list.  For
     example:

          a = [1, [], 3, [], 5]

     By default, the `Octave:empty-list-elements' warning is enabled.

`Octave:fortran-indexing'
     If the `Octave:fortran-indexing' warning is enabled, a warning is
     printed for expressions which select elements of a two-dimensional
     matrix using a single index.  By default, the
     `Octave:fortran-indexing' warning is disabled.

`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: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:matlab-incompatible'
     Print warnings for Octave language features that may cause
     compatibility problems with MATLAB.

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

`Octave:single-quote-string'
     Print warning if a single quote character is used to introduce a
     string constant.

`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:string-concat'
     If the `Octave:string-concat' warning is enabled, print a warning
     when concatenating a mixture of double and single quoted strings.
     By default, the `Octave:string-concat' 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::


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

 -- Built-in Function: VAL = debug_on_warning ()
 -- Built-in Function: OLD_VAL = debug_on_warning (NEW_VAL)
     Query or set the internal variable that controls whether Octave
     will try to enter the debugger when a warning is encountered.

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


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
     In debugging mode, quit debugging mode and continue execution.

     *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
     In debugging mode, quit debugging mode and return to the top level.

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

   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, LINE, ...)
     Set a breakpoint in a function
    `func'
          String representing the function name.  When already in debug
          mode this should be left out and only the line should be
          given.

    `line'
          Line number you would like the breakpoint to be set on.
          Multiple lines might be given as separate arguments or as a
          vector.

     The rline returned is the real line that the breakpoint was set at.

     *See also:* *note dbclear: doc-dbclear, *note dbstatus:
     doc-dbstatus, *note dbstep: doc-dbstep.

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)
     => 27

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: lst = dbstatus (FUNC)
     Return a vector containing the lines on which a function has
     breakpoints set.
    `func'
          String representing the function name.  When already in debug
          mode this should be left out.

     *See also:* *note dbclear: doc-dbclear, *note dbwhere: doc-dbwhere.

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

 -- Loadable Function:  dbclear (FUNC, LINE, ...)
     Delete a breakpoint in a function
    `func'
          String representing the function name.  When already in debug
          mode this should be left out and only the line should be
          given.

    `line'
          Line number where you would like to remove the breakpoint.
          Multiple lines might be given as separate arguments or as a
          vector.
     No checking is done to make sure that the line you requested is
     really a breakpoint.  If you get the wrong line nothing will
     happen.

     *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 ()
     Show where we are in the code

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

 -- Loadable Function:  dbtype ()
     List script file with line numbers.

     *See also:* *note dbclear: doc-dbclear, *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 debug mode is on, otherwise false.

     *See also:* *note dbstack: doc-dbstack, *note dbclear:
     doc-dbclear, *note dbstop: doc-dbstop, *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
     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.

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


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

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

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

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

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

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


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

 -- 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 extra blank space around column number labels
          producing more compact output with more data per page.

    `loose'
          Insert blank lines above and below column number labels 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)
     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::.

     *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)
     Query or set the internal variable that specifies the options to
     pass to the pager.

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

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

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

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

    `-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 upper case 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 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", ...)
     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.

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

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

 -- Built-in Function: VAL = save_precision ()
 -- Built-in Function: OLD_VAL = save_precision (NEW_VAL)
     Query or set the internal variable that specifies the number of
     digits to keep when saving data in text format.

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

     *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", ...)
     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 the
     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, 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 one more:
        * "headerlines":
     The first VALUE number of lines of STR are skipped.

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

 -- 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 (...)
     Read data from a text file.

     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 one more:
        * "headerlines":
     The first VALUE number of lines of STR are skipped.

     The optional input, N, specifes the number of lines to be read from
     the file, associated with FID.

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

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

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

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

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

     *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)
     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"'

     *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)
     Close the specified file.  If successful, `fclose' returns 0,
     otherwise, it returns -1.

     *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, 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
     lower-case letters and `%X' uses upper-case.  *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
     lower-case letters and `%E' uses upper-case.  *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 lower-case letters and `%G' uses upper-case.
     *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] = fscanf (FID, TEMPLATE, SIZE)
 -- Built-in Function: [V1, V2, ..., COUNT] = 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.

     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] = scanf (TEMPLATE, SIZE)
 -- Built-in Function: [V1, V2, ..., COUNT]] = 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] = sscanf (STRING, TEMPLATE, SIZE)
 -- Built-in Function: [V1, V2, ..., COUNT] = 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.

     *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 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 value required to request that `fseek' 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.

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


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 Plotting::
* 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 Plotting,  Up: High-Level Plotting

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

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

     *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 (...)
     Plots 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.

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

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

     *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 provides a handle to the "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 ())

     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 return value H provides a handle to the bar series
     object.  See `bar' for a description of the use of the bar series.

     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.

     *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 = ones (1, length (x))*2.*x;
          stem (x, y, "r");

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

     The return value of `stem' is a vector of "stem series" graphics
     handles, with one handle per column of the variable Y.  This
     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.

     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 provides a list of handles to the the
     parts of the vector field (body, arrow and marker).

     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 plot: doc-plot, *note compass: doc-compass,
     *note polar: doc-polar, *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 (...)
     Make a two-dimensional plot given the polar coordinates THETA and
     RHO.

     The optional third argument specifies the line type.

     *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 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 provides a handle to the patch object.

     *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 provides a handle list to patch,
     surface and text objects generating this 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 provides a quiver group that 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 provides a quiver group that 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 provides a list of handles to the the
     parts of the vector field (body, arrow and marker).

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

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

 -- 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 provides a list of handles to the the
     parts of the vector field (body, arrow and marker).

          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 the
     `patch'.  The optional return value H provides a handle to area
     series object representing the patches of the areas.

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

   The axis function may be used to change the axis limits of an
existing plot and various other axis properties, such as the aspect
ratio and the appearance of tic marks.

 -- Function File:  axis ()
 -- Function File:  axis ([X_lo, X_hi])
 -- Function File:  axis ([X_lo, X_hi, Y_lo, Y_hi])
 -- Function File:  axis ([X_lo, X_hi, Y_lo, Y_hi, Z_lo, Z_hi])
 -- Function File:  axis (OPTION)
 -- Function File:  axis (..., OPTION)
 -- Function File:  axis (H, ...)
 -- Function File: LIMITS = axis ()
     Set axis limits for plots.

     The argument LIMITS should be a 2-, 4-, or 6-element vector.  The
     first and second elements specify the lower and upper limits for
     the x-axis.  The third and fourth specify the limits for the
     y-axis, and the fifth and sixth specify the limits for the z-axis.

     Without any arguments, `axis' turns autoscaling on.

     With one output argument, `x = axis' returns the current axes.

     The vector argument specifying limits is optional, and additional
     string arguments may be used to specify various axis properties.
     For example,

          axis ([1, 2, 3, 4], "square");

     forces a square aspect ratio, and

          axis ("tic", "labely");

     turns tic marks on for all axes and tic mark labels on for the
     y-axis only.

     The following options control the aspect ratio of the axes.

    "square"
          Force a square aspect ratio.

    "equal"
          Force x distance to equal y-distance.

    "normal"
          Restore the balance.

     The following options control the way axis limits are interpreted.

    "auto"
          Set the specified axes to have nice limits around the data or
          all if no axes are specified.

    "manual"
          Fix the current axes limits.

    "tight"
          Fix axes to the limits of the data.

     The option `"image"' is equivalent to `"tight"' and `"equal"'.

     The following options affect the appearance of tic marks.

    "on"
          Turn tic marks and labels on for all axes.

    "off"
          Turn tic marks off for all axes.

    "tic[xyz]"
          Turn tic marks on for all axes, or turn them on for the
          specified axes and off for the remainder.

    "label[xyz]"
          Turn tic labels on for all axes, or turn them on for the
          specified axes and off for the remainder.

    "nolabel"
          Turn tic labels off for all axes.
     Note, if there are no tic marks for an axis, there can be no
     labels.

     The following options affect the direction of increasing values on
     the axes.

    "ij"
          Reverse y-axis, so lower values are nearer the top.

    "xy"
          Restore y-axis, so higher values are nearer the top.

     If an axes handle is passed as the first argument, then operate on
     this axes rather than the current axes.

   Similarly the axis limits of the colormap can be changed with the
caxis function.

 -- Function File:  caxis (LIMITS)
 -- Function File:  caxis (H, ...)
     Set color axis limits for plots.

     The argument LIMITS should be a 2-element vector specifying the
     lower and upper limits to assign to the first and last value in the
     colormap.  Values outside this range are clamped to the first and
     last colormap entries.

     If LIMITS is 'auto', then automatic colormap scaling is applied,
     whereas if LIMITS is 'manual' the colormap scaling is set to
     manual.

     Called without any arguments to current color axis limits are
     returned.

     If an axes handle is passed as the first argument, then operate on
     this axes rather than the current axes.

   The `xlim', `ylim', and `zlim' functions may be used to get or set
individual axis limits.  Each has the same form.

 -- Function File: XL = xlim ()
 -- Function File:  xlim (XL)
 -- Function File: M = xlim ('mode')
 -- Function File:  xlim (M)
 -- Function File:  xlim (H, ...)
     Get or set the limits of the x-axis of the current plot.  Called
     without arguments `xlim' returns the x-axis limits of the current
     plot.  If passed a two element vector XL, the limits of the x-axis
     are set to this value.

     The current mode for calculation of the x-axis can be returned
     with a call `xlim ('mode')', and can be either 'auto' or 'manual'.
     The current plotting mode can be set by passing either 'auto' or
     'manual' as the argument.

     If passed a handle as the first argument, then operate on this
     handle rather than the current axes handle.

     *See also:* *note ylim: doc-ylim, *note zlim: doc-zlim, *note set:
     doc-set, *note get: doc-get, *note gca: doc-gca.

* Menu:

* Two-dimensional Function Plotting::


File: octave.info,  Node: Two-dimensional Function Plotting,  Up: Two-Dimensional Plots

15.2.1.1 Two-dimensional Function Plotting
..........................................

Octave can plot a function from a function handle inline function or
string defining the function without the user needing to explicitly
create the data to be plotted.  The function `fplot' also generates
two-dimensional plots with linear axes using a function name and limits
for the range of the x-coordinate instead of the x and y data.  For
example,

     fplot (@sin, [-10, 10], 201);

produces a plot that is equivalent to the one above, but also includes a
legend displaying the name of the plotted function.

 -- Function File:  fplot (FN, LIMITS)
 -- Function File:  fplot (FN, LIMITS, TOL)
 -- Function File:  fplot (FN, LIMITS, N)
 -- Function File:  fplot (..., FMT)
     Plot a function FN, within the defined limits.  FN an be either a
     string, a function handle or an inline function.  The limits of
     the plot are given by LIMITS of the form `[XLO, XHI]' or `[XLO,
     XHI, YLO, YHI]'.  TOL is the default tolerance to use for the
     plot, and if TOL is an integer it is assumed that it defines the
     number points to use in the plot.  The FMT argument is passed to
     the plot command.

             fplot ("cos", [0, 2*pi])
             fplot ("[cos(x), sin(x)]", [0, 2*pi])

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

   Other functions that can create two-dimensional plots directly from a
function include `ezplot', `ezcontour', `ezcontourf' and `ezpolar'.

 -- Function File:  ezplot (F)
 -- Function File:  ezplot (FX, FY)
 -- Function File:  ezplot (..., DOM)
 -- Function File:  ezplot (..., N)
 -- Function File:  ezplot (H, ...)
 -- Function File: H = ezplot (...)
     Plots in two-dimensions the curve defined by F.  The function F
     may be a string, inline function or function handle and can have
     either one or two variables.  If F has one variable, then the
     function is plotted over the domain `-2*pi < X < 2*pi' with 500
     points.

     If F has two variables then `F(X,Y) = 0' is calculated over the
     meshed domain `-2*pi < X | Y < 2*pi' with 60 by 60 in the mesh.
     For example:

          ezplot (@(X, Y) X .^ 2 - Y .^ 2 - 1)

     If two functions are passed as strings, inline functions or
     function handles, then the parametric function

          X = FX (T)
          Y = FY (T)

     is plotted over the domain `-2*pi < T < 2*pi' with 500 points.

     If DOM is a two element vector, it represents the minimum and
     maximum value of X, Y and T.  If it is a four element vector, then
     the minimum and maximum values of X and T are determined by the
     first two elements and the minimum and maximum of Y by the second
     pair of elements.

     N is a scalar defining the number of points to use in plotting the
     function.

     The optional return value H provides a list of handles to the the
     line objects plotted.

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

 -- Function File:  ezcontour (F)
 -- Function File:  ezcontour (..., DOM)
 -- Function File:  ezcontour (..., N)
 -- Function File:  ezcontour (H, ...)
 -- Function File: H = ezcontour (...)
     Plots the contour lines of a function.  F is a string, inline
     function or function handle with two arguments defining the
     function.  By default the plot is over the domain `-2*pi < X <
     2*pi' and `-2*pi < Y < 2*pi' with 60 points in each dimension.

     If DOM is a two element vector, it represents the minimum and
     maximum value of both X and Y.  If DOM is a four element vector,
     then the minimum and maximum value of X and Y are specify
     separately.

     N is a scalar defining the number of points to use in each
     dimension.

     The optional return value H provides a list of handles to the the
     parts of the vector field (body, arrow and marker).

          f = @(x,y) sqrt(abs(x .* y)) ./ (1 + x.^2 + y.^2);
          ezcontour (f, [-3, 3]);

     *See also:* *note ezplot: doc-ezplot, *note ezcontourf:
     doc-ezcontourf, *note ezsurfc: doc-ezsurfc, *note ezmeshc:
     doc-ezmeshc.

 -- Function File:  ezcontourf (F)
 -- Function File:  ezcontourf (..., DOM)
 -- Function File:  ezcontourf (..., N)
 -- Function File:  ezcontourf (H, ...)
 -- Function File: H = ezcontourf (...)
     Plots the filled contour lines of a function.  F is a string,
     inline function or function handle with two arguments defining the
     function.  By default the plot is over the domain `-2*pi < X <
     2*pi' and `-2*pi < Y < 2*pi' with 60 points in each dimension.

     If DOM is a two element vector, it represents the minimum and
     maximum value of both X and Y.  If DOM is a four element vector,
     then the minimum and maximum value of X and Y are specify
     separately.

     N is a scalar defining the number of points to use in each
     dimension.

     The optional return value H provides a list of handles to the the
     parts of the vector field (body, arrow and marker).

          f = @(x,y) sqrt(abs(x .* y)) ./ (1 + x.^2 + y.^2);
          ezcontourf (f, [-3, 3]);

     *See also:* *note ezplot: doc-ezplot, *note ezcontour:
     doc-ezcontour, *note ezsurfc: doc-ezsurfc, *note ezmeshc:
     doc-ezmeshc.

 -- Function File:  ezpolar (F)
 -- Function File:  ezpolar (..., DOM)
 -- Function File:  ezpolar (..., N)
 -- Function File:  ezpolar (H, ...)
 -- Function File: H = ezpolar (...)
     Plots in polar plot defined by a function.  The function F is
     either a string, inline function or function handle with one
     arguments defining the function.  By default the plot is over the
     domain `0 < X < 2*pi' with 60 points.

     If DOM is a two element vector, it represents the minimum and
     maximum value of both T.  N is a scalar defining the number of
     points to use.

     The optional return value H provides a list of handles to the the
     parts of the vector field (body, arrow and marker).

          ezpolar (@(t) 1 + sin (t));

     *See also:* *note polar: doc-polar, *note ezplot: doc-ezplot,
     *note ezsurf: doc-ezsurf, *note ezmesh: doc-ezmesh.


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

15.2.2 Three-Dimensional Plotting
---------------------------------

The function `mesh' produces mesh surface plots.  For example,

     tx = ty = linspace (-8, 8, 41)';
     [xx, yy] = meshgrid (tx, ty);
     r = sqrt (xx .^ 2 + yy .^ 2) + eps;
     tz = sin (r) ./ r;
     mesh (tx, ty, tz);

produces the familiar "sombrero" plot shown in *note fig:mesh::.  Note
the use of the function `meshgrid' to create matrices of X and Y
coordinates to use for plotting the Z data.  The `ndgrid' function is
similar to `meshgrid', but works for N-dimensional matrices.


+---------------------------------+
| Image unavailable in text mode. |
+---------------------------------+
Figure 15.5: Mesh plot.

   The `meshc' function is similar to `mesh', but also produces a plot
of contours for the surface.

   The `plot3' function displays arbitrary three-dimensional data,
without requiring it to form a surface.  For example,

     t = 0:0.1:10*pi;
     r = linspace (0, 1, numel (t));
     z = linspace (0, 1, numel (t));
     plot3 (r.*sin(t), r.*cos(t), z);

displays the spiral in three dimensions shown in *note fig:plot3::.


+---------------------------------+
| Image unavailable in text mode. |
+---------------------------------+
Figure 15.6: Three-dimensional spiral.

   Finally, the `view' function changes the viewpoint for
three-dimensional plots.

 -- Function File:  mesh (X, Y, Z)
 -- Function File:  mesh (Z)
 -- Function File:  mesh (..., C)
 -- Function File:  mesh (HAX, ...)
 -- Function File: H = mesh (...)
     Plot a mesh given matrices X, and Y from `meshgrid' and a matrix Z
     corresponding to the X and Y coordinates of the mesh.  If X and Y
     are vectors, then a typical vertex is (X(j), Y(i), Z(i,j)).  Thus,
     columns of Z correspond to different X values and rows of Z
     correspond to different Y values.

     The color of the mesh is derived from the `colormap' and the value
     of Z.  Optionally the color of the mesh can be specified
     independent of Z, by adding a fourth matrix, C.

     *See also:* *note colormap: doc-colormap, *note contour:
     doc-contour, *note meshgrid: doc-meshgrid, *note surf: doc-surf.

 -- Function File:  meshc (X, Y, Z)
     Plot a mesh and contour given matrices X, and Y from `meshgrid'
     and a matrix Z corresponding to the X and Y coordinates of the
     mesh.  If X and Y are vectors, then a typical vertex is (X(j),
     Y(i), Z(i,j)).  Thus, columns of Z correspond to different X
     values and rows of Z correspond to different Y values.

     *See also:* *note meshgrid: doc-meshgrid, *note mesh: doc-mesh,
     *note contour: doc-contour.

 -- Function File:  meshz (X, Y, Z)
     Plot a curtain mesh given matrices X, and Y from `meshgrid' and a
     matrix Z corresponding to the X and Y coordinates of the mesh.  If
     X and Y are vectors, then a typical vertex is (X(j), Y(i),
     Z(i,j)).  Thus, columns of Z correspond to different X values and
     rows of Z correspond to different Y values.

     *See also:* *note meshgrid: doc-meshgrid, *note mesh: doc-mesh,
     *note contour: doc-contour.

 -- Function File:  hidden (MODE)
 -- Function File:  hidden ()
     Manipulation the mesh hidden line removal.  Called with no argument
     the hidden line removal is toggled.  The argument MODE can be
     either 'on' or 'off' and the set of the hidden line removal is set
     accordingly.

     *See also:* *note mesh: doc-mesh, *note meshc: doc-meshc, *note
     surf: doc-surf.

 -- Function File:  surf (X, Y, Z)
 -- Function File:  surf (Z)
 -- Function File:  surf (..., C)
 -- Function File:  surf (HAX, ...)
 -- Function File: H = surf (...)
     Plot a surface given matrices X, and Y from `meshgrid' and a
     matrix Z corresponding to the X and Y coordinates of the mesh.  If
     X and Y are vectors, then a typical vertex is (X(j), Y(i),
     Z(i,j)).  Thus, columns of Z correspond to different X values and
     rows of Z correspond to different Y values.

     The color of the surface is derived from the `colormap' and the
     value of Z.  Optionally the color of the surface can be specified
     independent of Z, by adding a fourth matrix, C.

     *See also:* *note colormap: doc-colormap, *note contour:
     doc-contour, *note meshgrid: doc-meshgrid, *note mesh: doc-mesh.

 -- Function File:  surfc (X, Y, Z)
     Plot a surface and contour given matrices X, and Y from `meshgrid'
     and a matrix Z corresponding to the X and Y coordinates of the
     mesh.  If X and Y are vectors, then a typical vertex is (X(j),
     Y(i), Z(i,j)).  Thus, columns of Z correspond to different X
     values and rows of Z correspond to different Y values.

     *See also:* *note meshgrid: doc-meshgrid, *note surf: doc-surf,
     *note contour: doc-contour.

 -- Function File:  surfl (X, Y, Z)
 -- Function File:  surfl (Z)
 -- Function File:  surfl (X, Y, Z, L)
 -- Function File:  surfl (X, Y, Z, L, P)
 -- Function File:  surfl (..., "light")
     Plot a lighted surface given matrices X, and Y from `meshgrid' and
     a matrix Z corresponding to the X and Y coordinates of the mesh.
     If X and Y are vectors, then a typical vertex is (X(j), Y(i),
     Z(i,j)).  Thus, columns of Z correspond to different X values and
     rows of Z correspond to different Y values.

     The light direction can be specified using L.  It can be given as
     2-element vector [azimuth, elevation] in degrees or as 3-element
     vector [lx, ly, lz].  The default value is rotated 45°
     counter-clockwise from the current view.

     The material properties of the surface can specified using a
     4-element vector P = [AM D SP EXP] which defaults to P = [0.55 0.6
     0.4 10].
    "AM" strength of ambient light

    "D" strength of diffuse reflection

    "SP" strength of specular reflection

    "EXP" specular exponent

     The default lighting mode "cdata", changes the cdata property to
     give the impression of a lighted surface.  Please note: the
     alternative "light" mode, which creates a light object to
     illuminate the surface is not implemented (yet).

     Example:

          colormap(bone);
          surfl(peaks);
          shading interp;

     *See also:* *note surf: doc-surf, *note diffuse: doc-diffuse,
     *note specular: doc-specular, *note surface: doc-surface.

 -- Function File:  surfnorm (X, Y, Z)
 -- Function File:  surfnorm (Z)
 -- Function File: [NX, NY, NZ] = surfnorm (...)
 -- Function File:  surfnorm (H, ...)
     Find the vectors normal to a meshgridded surface.  The meshed
     gridded surface is defined by X, Y, and Z.  If X and Y are not
     defined, then it is assumed that they are given by

          [X, Y] = meshgrid (1:size(Z, 1),
                               1:size(Z, 2));

     If no return arguments are requested, a surface plot with the
     normal vectors to the surface is plotted.  Otherwise the
     components of the normal vectors at the mesh gridded points are
     returned in NX, NY, and NZ.

     The normal vectors are calculated by taking the cross product of
     the diagonals of each of the quadrilaterals in the meshgrid to
     find the normal vectors of the centers of these quadrilaterals.
     The four nearest normal vectors to the meshgrid points are then
     averaged to obtain the normal to the surface at the meshgridded
     points.

     An example of the use of `surfnorm' is

          surfnorm (peaks (25));

     *See also:* *note surf: doc-surf, *note quiver3: doc-quiver3.

 -- Function File:  diffuse (SX, SY, SZ, LV)
     Calculate diffuse reflection strength of a surface defined by the
     normal vector elements SX, SY, SZ.  The light vector can be
     specified using parameter LV.  It can be given as 2-element vector
     [azimuth, elevation] in degrees or as 3-element vector [lx, ly,
     lz].

     *See also:* *note specular: doc-specular, *note surfl: doc-surfl.

 -- Function File:  specular (SX, SY, SZ, LV, VV)
 -- Function File:  specular (SX, SY, SZ, LV, VV, SE)
     Calculate specular reflection strength of a surface defined by the
     normal vector elements SX, SY, SZ using Phong's approximation.
     The light and view vectors can be specified using parameter LV and
     VV respectively.  Both can be given as 2-element vectors [azimuth,
     elevation] in degrees or as 3-element vector [x, y, z].  An
     optional 6th argument describes the specular exponent (spread) SE.

     *See also:* *note surfl: doc-surfl, *note diffuse: doc-diffuse.

 -- Function File: [XX, YY, ZZ] = meshgrid (X, Y, Z)
 -- Function File: [XX, YY] = meshgrid (X, Y)
 -- Function File: [XX, YY] = meshgrid (X)
     Given vectors of X and Y and Z coordinates, and returning 3
     arguments, return three-dimensional arrays corresponding to the X,
     Y, and Z coordinates of a mesh.  When returning only 2 arguments,
     return matrices corresponding to the X and Y coordinates of a
     mesh.  The rows of XX are copies of X, and the columns of YY are
     copies of Y.  If Y is omitted, then it is assumed to be the same
     as X, and Z is assumed the same as Y.

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

 -- Function File: [Y1, Y2, ..., Yn] = ndgrid (X1, X2, ..., Xn)
 -- Function File: [Y1, Y2, ..., Yn] = ndgrid (X)
     Given n vectors X1, ... Xn, `ndgrid' returns n arrays of dimension
     n. The elements of the i-th output argument contains the elements
     of the vector Xi repeated over all dimensions different from the
     i-th dimension.  Calling ndgrid with only one input argument X is
     equivalent of calling ndgrid with all n input arguments equal to X:

     [Y1, Y2, ...,  Yn] = ndgrid (X, ..., X)

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

 -- Function File:  plot3 (ARGS)
     Produce three-dimensional plots.  Many different combinations of
     arguments are possible.  The simplest form is

          plot3 (X, Y, Z)

     in which the arguments are taken to be the vertices of the points
     to be plotted in three dimensions.  If all arguments are vectors
     of the same length, then a single continuous line is drawn.  If
     all arguments are matrices, then each column of the matrices is
     treated as a separate line.  No attempt is made to transpose the
     arguments to make the number of rows match.

     If only two arguments are given, as

          plot3 (X, C)

     the real and imaginary parts of the second argument are used as
     the Y and Z coordinates, respectively.

     If only one argument is given, as

          plot3 (C)

     the real and imaginary parts of the argument are used as the Y and
     Z values, and they are plotted versus their index.

     Arguments may also be given in groups of three as

          plot3 (X1, Y1, Z1, X2, Y2, Z2, ...)

     in which each set of three arguments is treated as a separate line
     or set of lines in three dimensions.

     To plot multiple one- or two-argument groups, separate each group
     with an empty format string, as

          plot3 (X1, C1, "", C2, "", ...)

     An example of the use of `plot3' is

             z = [0:0.05:5];
             plot3 (cos(2*pi*z), sin(2*pi*z), z, ";helix;");
             plot3 (z, exp(2i*pi*z), ";complex sinusoid;");

     *See also:* *note plot: doc-plot, *note xlabel: doc-xlabel, *note
     ylabel: doc-ylabel, *note zlabel: doc-zlabel, *note title:
     doc-title, *note print: doc-print.

 -- Function File: [AZIMUTH, ELEVATION] = view ()
 -- Function File:  view (AZIMUTH, ELEVATION)
 -- Function File:  view ([AZIMUTH, ELEVATION])
 -- Function File:  view ([X, Y, Z])
 -- Function File:  view (DIMS)
 -- Function File:  view (AX, ...)
     Query or set the viewpoint for the current axes.  The parameters
     AZIMUTH and ELEVATION can be given as two arguments or as
     2-element vector.  The viewpoint can also be given with Cartesian
     coordinates X, Y, and Z.  The call `view (2)' sets the viewpoint
     to AZIMUTH = 0 and ELEVATION = 90, which is the default for 2-D
     graphs.  The call `view (3)' sets the viewpoint to AZIMUTH = -37.5
     and ELEVATION = 30, which is the default for 3-D graphs.  If AX is
     given, the viewpoint is set for this axes, otherwise it is set for
     the current axes.

 -- Function File:  slice (X, Y, Z, V, SX, SY, SZ)
 -- Function File:  slice (X, Y, Z, V, XI, YI, ZI)
 -- Function File:  slice (V, SX, SY, SZ)
 -- Function File:  slice (V, XI, YI, ZI)
 -- Function File: H = slice (...)
 -- Function File: H = slice (..., METHOD)
     Plot slices of 3-D data/scalar fields.  Each element of the
     3-dimensional array V represents a scalar value at a location
     given by the parameters X, Y, and Z.  The parameters X, X, and Z
     are either 3-dimensional arrays of the same size as the array V in
     the "meshgrid" format or vectors.  The parameters XI, etc. respect
     a similar format to X, etc., and they represent the points at
     which the array VI is interpolated using interp3.  The vectors SX,
     SY, and SZ contain points of orthogonal slices of the respective
     axes.

     If X, Y, Z are omitted, they are assumed to be `x = 1:size (V,
     2)', `y = 1:size (V, 1)' and `z = 1:size (V, 3)'.

     METHOD is one of:

    "nearest"
          Return the nearest neighbor.

    "linear"
          Linear interpolation from nearest neighbors.

    "cubic"
          Cubic interpolation from four nearest neighbors (not
          implemented yet).

    "spline"
          Cubic spline interpolation--smooth first and second
          derivatives throughout the curve.

     The default method is `"linear"'.  The optional return value H is
     a vector of handles to the surface graphic objects.

     Examples:

          [x, y, z] = meshgrid (linspace (-8, 8, 32));
          v = sin (sqrt (x.^2 + y.^2 + z.^2)) ./ (sqrt (x.^2 + y.^2 + z.^2));
          slice (x, y, z, v, [], 0, []);
          [xi, yi] = meshgrid (linspace (-7, 7));
          zi = xi + yi;
          slice (x, y, z, v, xi, yi, zi);

     *See also:* *note interp3: doc-interp3, *note surface:
     doc-surface, *note pcolor: doc-pcolor.

 -- Function File:  ribbon (X, Y, WIDTH)
 -- Function File:  ribbon (Y)
 -- Function File: H = ribbon (...)
     Plot a ribbon plot for the columns of Y vs.  X.  The optional
     parameter WIDTH specifies the width of a single ribbon (default is
     0.75).  If X is omitted, a vector containing the row numbers is
     assumed (1:rows(Y)).  If requested, return a vector H of the
     handles to the surface objects.

     *See also:* *note gca: doc-gca, *note colorbar: doc-colorbar.

 -- Function File:  shading (TYPE)
 -- Function File:  shading (AX, ...)
     Set the shading of surface or patch graphic objects.  Valid
     arguments for TYPE are

    "flat"
          Single colored patches with invisible edges.

    "faceted"
          Single colored patches with visible edges.

    "interp"
          Color between patch vertices are interpolated and the patch
          edges are invisible.

     If AX is given the shading is applied to axis AX instead of the
     current axis.

 -- Function File:  scatter3 (X, Y, Z, S, C)
 -- Function File:  scatter3 (..., 'filled')
 -- Function File:  scatter3 (..., STYLE)
 -- Function File:  scatter3 (..., PROP, VAL)
 -- Function File:  scatter3 (H, ...)
 -- Function File: H = scatter3 (...)
     Plot a scatter plot of the data in 3D.  A marker is plotted at
     each point defined by the points in the vectors X, Y and Z.  The
     size of the markers used is determined by S, which can be a scalar
     or a vector of the same length of X, Y and Z.  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, y, z] = peaks (20);
          scatter3 (x(:), y(:), z(:), [], z(:));

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

* Menu:

* Three-dimensional Function Plotting::
* Three-dimensional Geometric Shapes::


File: octave.info,  Node: Three-dimensional Function Plotting,  Next: Three-dimensional Geometric Shapes,  Up: Three-Dimensional Plotting

15.2.2.1 Three-dimensional Function Plotting
............................................

 -- Function File:  ezplot3 (FX, FY, FZ)
 -- Function File:  ezplot3 (..., DOM)
 -- Function File:  ezplot3 (..., N)
 -- Function File:  ezplot3 (H, ...)
 -- Function File: H = ezplot3 (...)
     Plots in three-dimensions the curve defined parametrically.  FX,
     FY, and FZ are strings, inline functions or function handles with
     one arguments defining the function.  By default the plot is over
     the domain `-2*pi < X < 2*pi' with 60 points.

     If DOM is a two element vector, it represents the minimum and
     maximum value of T.  N is a scalar defining the number of points
     to use.

     The optional return value H provides a list of handles to the the
     parts of the vector field (body, arrow and marker).

          fx = @(t) cos (t);
          fy = @(t) sin (t);
          fz = @(t) t;
          ezplot3 (fx, fy, fz, [0, 10*pi], 100);

     *See also:* *note plot3: doc-plot3, *note ezplot: doc-ezplot,
     *note ezsurf: doc-ezsurf, *note ezmesh: doc-ezmesh.

 -- Function File:  ezmesh (F)
 -- Function File:  ezmesh (FX, FY, FZ)
 -- Function File:  ezmesh (..., DOM)
 -- Function File:  ezmesh (..., N)
 -- Function File:  ezmesh (..., 'circ')
 -- Function File:  ezmesh (H, ...)
 -- Function File: H = ezmesh (...)
     Plots the mesh defined by a function.  F is a string, inline
     function or function handle with two arguments defining the
     function.  By default the plot is over the domain `-2*pi < X <
     2*pi' and `-2*pi < Y < 2*pi' with 60 points in each dimension.

     If DOM is a two element vector, it represents the minimum and
     maximum value of both X and Y.  If DOM is a four element vector,
     then the minimum and maximum value of X and Y are specify
     separately.

     N is a scalar defining the number of points to use in each
     dimension.

     If three functions are passed, then plot the parametrically defined
     function `[FX (S, T), FY (S, T), FZ (S, T)]'.

     If the argument 'circ' is given, then the function is plotted over
     a disk centered on the middle of the domain DOM.

     The optional return value H provides a list of handles to the the
     parts of the vector field (body, arrow and marker).

          f = @(x,y) sqrt(abs(x .* y)) ./ (1 + x.^2 + y.^2);
          ezmesh (f, [-3, 3]);

     An example of a parametrically defined function is

          fx = @(s,t) cos (s) .* cos(t);
          fy = @(s,t) sin (s) .* cos(t);
          fz = @(s,t) sin(t);
          ezmesh (fx, fy, fz, [-pi, pi, -pi/2, pi/2], 20);

     *See also:* *note ezplot: doc-ezplot, *note ezsurf: doc-ezsurf,
     *note ezsurfc: doc-ezsurfc, *note ezmeshc: doc-ezmeshc.

 -- Function File:  ezmeshc (F)
 -- Function File:  ezmeshc (FX, FY, FZ)
 -- Function File:  ezmeshc (..., DOM)
 -- Function File:  ezmeshc (..., N)
 -- Function File:  ezmeshc (..., 'circ')
 -- Function File:  ezmeshc (H, ...)
 -- Function File: H = ezmeshc (...)
     Plots the mesh and contour lines defined by a function.  F is a
     string, inline function or function handle with two arguments
     defining the function.  By default the plot is over the domain
     `-2*pi < X < 2*pi' and `-2*pi < Y < 2*pi' with 60 points in each
     dimension.

     If DOM is a two element vector, it represents the minimum and
     maximum value of both X and Y.  If DOM is a four element vector,
     then the minimum and maximum value of X and Y are specify
     separately.

     N is a scalar defining the number of points to use in each
     dimension.

     If three functions are passed, then plot the parametrically defined
     function `[FX (S, T), FY (S, T), FZ (S, T)]'.

     If the argument 'circ' is given, then the function is plotted over
     a disk centered on the middle of the domain DOM.

     The optional return value H provides a list of handles to the the
     parts of the vector field (body, arrow and marker).

          f = @(x,y) sqrt(abs(x .* y)) ./ (1 + x.^2 + y.^2);
          ezmeshc (f, [-3, 3]);

     *See also:* *note ezplot: doc-ezplot, *note ezsurfc: doc-ezsurfc,
     *note ezsurf: doc-ezsurf, *note ezmesh: doc-ezmesh.

 -- Function File:  ezsurf (F)
 -- Function File:  ezsurf (FX, FY, FZ)
 -- Function File:  ezsurf (..., DOM)
 -- Function File:  ezsurf (..., N)
 -- Function File:  ezsurf (..., 'circ')
 -- Function File:  ezsurf (H, ...)
 -- Function File: H = ezsurf (...)
     Plots the surface defined by a function.  F is a string, inline
     function or function handle with two arguments defining the
     function.  By default the plot is over the domain `-2*pi < X <
     2*pi' and `-2*pi < Y < 2*pi' with 60 points in each dimension.

     If DOM is a two element vector, it represents the minimum and
     maximum value of both X and Y.  If DOM is a four element vector,
     then the minimum and maximum value of X and Y are specify
     separately.

     N is a scalar defining the number of points to use in each
     dimension.

     If three functions are passed, then plot the parametrically defined
     function `[FX (S, T), FY (S, T), FZ (S, T)]'.

     If the argument 'circ' is given, then the function is plotted over
     a disk centered on the middle of the domain DOM.

     The optional return value H provides a list of handles to the the
     parts of the vector field (body, arrow and marker).

          f = @(x,y) sqrt(abs(x .* y)) ./ (1 + x.^2 + y.^2);
          ezsurf (f, [-3, 3]);

     An example of a parametrically defined function is

          fx = @(s,t) cos (s) .* cos(t);
          fy = @(s,t) sin (s) .* cos(t);
          fz = @(s,t) sin(t);
          ezsurf (fx, fy, fz, [-pi, pi, -pi/2, pi/2], 20);

     *See also:* *note ezplot: doc-ezplot, *note ezmesh: doc-ezmesh,
     *note ezsurfc: doc-ezsurfc, *note ezmeshc: doc-ezmeshc.

 -- Function File:  ezsurfc (F)
 -- Function File:  ezsurfc (FX, FY, FZ)
 -- Function File:  ezsurfc (..., DOM)
 -- Function File:  ezsurfc (..., N)
 -- Function File:  ezsurfc (..., 'circ')
 -- Function File:  ezsurfc (H, ...)
 -- Function File: H = ezsurfc (...)
     Plots the surface and contour lines defined by a function.  F is a
     string, inline function or function handle with two arguments
     defining the function.  By default the plot is over the domain
     `-2*pi < X < 2*pi' and `-2*pi < Y < 2*pi' with 60 points in each
     dimension.

     If DOM is a two element vector, it represents the minimum and
     maximum value of both X and Y.  If DOM is a four element vector,
     then the minimum and maximum value of X and Y are specify
     separately.

     N is a scalar defining the number of points to use in each
     dimension.

     If three functions are passed, then plot the parametrically defined
     function `[FX (S, T), FY (S, T), FZ (S, T)]'.

     If the argument 'circ' is given, then the function is plotted over
     a disk centered on the middle of the domain DOM.

     The optional return value H provides a list of handles to the the
     parts of the vector field (body, arrow and marker).

          f = @(x,y) sqrt(abs(x .* y)) ./ (1 + x.^2 + y.^2);
          ezsurfc (f, [-3, 3]);

     *See also:* *note ezplot: doc-ezplot, *note ezmeshc: doc-ezmeshc,
     *note ezsurf: doc-ezsurf, *note ezmesh: doc-ezmesh.


File: octave.info,  Node: Three-dimensional Geometric Shapes,  Prev: Three-dimensional Function Plotting,  Up: Three-Dimensional Plotting

15.2.2.2 Three-dimensional Geometric Shapes
...........................................

 -- Function File:  cylinder
 -- Function File:  cylinder (R)
 -- Function File:  cylinder (R, N)
 -- Function File: [X, Y, Z] = cylinder (...)
 -- Function File:  cylinder (AX, ...)
     Generates three matrices in `meshgrid' format, such that `surf (X,
     Y, Z)' generates a unit cylinder.  The matrices are of size
     `N+1'-by-`N+1'.  R is a vector containing the radius along the
     z-axis.  If N or R are omitted then default values of 20 or [1 1]
     are assumed.

     Called with no return arguments, `cylinder' calls directly `surf
     (X, Y, Z)'.  If an axes handle AX is passed as the first argument,
     the surface is plotted to this set of axes.

     Examples:

          [x, y, z] = cylinder (10:-1:0,50);
          surf (x, y, z);
          title ("a cone")

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

 -- Function File: [X, Y, Z] = sphere (N)
 -- Function File:  sphere (H, ...)
     Generates three matrices in `meshgrid' format, such that `surf (X,
     Y, Z)' generates a unit sphere.  The matrices of `N+1'-by-`N+1'.
     If N is omitted then a default value of 20 is assumed.

     Called with no return arguments, `sphere' call directly `surf (X,
     Y, Z)'.  If an axes handle is passed as the first argument, the
     surface is plotted to this set of axes.

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

 -- Function File: [X, Y, Z] = ellipsoid (XC, YC, ZC, XR, YR, ZR, N)
 -- Function File:  ellipsoid (H, ...)
     Generate three matrices in `meshgrid' format that define an
     ellipsoid.  Called with no return arguments, `ellipsoid' calls
     directly `surf (X, Y, Z)'.  If an axes handle is passed as the
     first argument, the surface is plotted to this set of axes.

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


File: octave.info,  Node: Plot Annotations,  Next: Multiple Plots on One Page,  Prev: Three-Dimensional Plotting,  Up: High-Level Plotting

15.2.3 Plot Annotations
-----------------------

You can add titles, axis labels, legends, and arbitrary text to an
existing plot.  For example:

     x = -10:0.1:10;
     plot (x, sin (x));
     title ("sin(x) for x = -10:0.1:10");
     xlabel ("x");
     ylabel ("sin (x)");
     text (pi, 0.7, "arbitrary text");
     legend ("sin (x)");

   The functions `grid' and `box' may also be used to add grid and
border lines to the plot.  By default, the grid is off and the border
lines are on.

 -- Function File:  title (STRING)
 -- Function File:  title (STRING, P1, V1, ...)
     Create a title object and return a handle to it.

 -- Function File:  legend (STR1, STR2, ...)
 -- Function File:  legend (MATSTR)
 -- Function File:  legend (CELL)
 -- Function File:  legend (..., "location", POS)
 -- Function File:  legend (..., "orientation", ORIENT)
 -- Function File:  legend (HAX, ...)
 -- Function File:  legend (HOBJS, ...)
 -- Function File:  legend (HAX, HOBJS, ...)
 -- Function File:  legend ("OPTION")
     Display a legend for the axes with handle HAX, or the current axes,
     using the specified strings as labels.  Legend entries may be
     specified as individual character string arguments, a character
     array, or a cell array of character strings.  If the handles,
     HOBJS, are not specified then the legend's strings will be
     associated with the axes' descendants.  Legend works on line
     graphs, bar graphs, etc.  A plot must exist before legend is
     called.

     The optional parameter POS specifies the location of the legend as
     follows:

          north      center top
          south      center bottom
          east       right center
          west       left center
          northeast  right top (default)
          northwest  left top
          southeast  right bottom
          southwest  left bottom

          outside    can be appended to any location string

     The optional parameter ORIENT determines if the key elements are
     placed vertically or horizontally.  The allowed values are
     "vertical" or "horizontal" with the default being "vertical".

     The following customizations are available using OPTION:

    "show"
          Show legend on the plot

    "hide"
          Hide legend on the plot

    "toggle"
          Toggles between "hide" and "show"

    "boxon"
          Show a box around legend

    "boxoff"
          Hide the box around legend

    "left"
          Place text to the left of the keys

    "right"
          Place text to the right of the keys

    "off"
          Delete the legend object

 -- Function File: H = text (X, Y, LABEL)
 -- Function File: H = text (X, Y, Z, LABEL)
 -- Function File: H = text (X, Y, LABEL, P1, V1, ...)
 -- Function File: H = text (X, Y, Z, LABEL, P1, V1, ...)
     Create a text object with text LABEL at position X, Y, Z on the
     current axes.  Property-value pairs following LABEL may be used to
     specify the appearance of the text.

   See *note Text Properties:: for the properties that you can set.

 -- Function File:  xlabel (STRING)
 -- Function File:  xlabel (H, STRING)
 -- Function File: H = xlabel (...)
 -- Function File:  ylabel (...)
 -- Function File:  zlabel (...)
     Specify x-, y-, or z-axis labels for the current axis.  If H is
     specified then label the axis defined by H.  The optional return
     value H provides a handle to the created label.

     *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 stairs: doc-stairs, *note
     title: doc-title.

 -- Function File:  clabel (C, H)
 -- Function File:  clabel (C, H, V)
 -- Function File:  clabel (C, H, "manual")
 -- Function File:  clabel (C)
 -- Function File:  clabel (C, H)
 -- Function File:  clabel (..., PROP, VAL, ...)
 -- Function File: H = clabel (...)
     Adds labels to the contours of a contour plot.  The contour plot
     is specified by the contour matrix C and optionally the
     contourgroup object H that are returned by `contour', `contourf'
     and `contour3'.  The contour labels are rotated and placed in the
     contour itself.

     By default, all contours are labeled.  However, the contours to
     label can be specified by the vector V.  If the "manual" argument
     is given then the contours to label can be selected with the mouse.

     Additional property/value pairs that are valid properties of text
     objects can be given and are passed to the underlying text
     objects.  Additionally, the property "LabelSpacing" is available
     allowing the spacing between labels on a contour (in points) to be
     specified.  The default is 144 points, or 2 inches.

     The returned value H is the set of text object that represent the
     contour labels.  The "userdata" property of the text objects
     contains the numerical value of the contour label.

     An example of the use of `clabel' is

          [c, h] = contour (peaks(), -4 : 6);
          clabel (c, h, -4 : 2 : 6, 'fontsize', 12);

     *See also:* *note contour: doc-contour, *note contourf:
     doc-contourf, *note contour3: doc-contour3, *note meshc:
     doc-meshc, *note surfc: doc-surfc, *note text: doc-text.

 -- Function File:  box (ARG)
 -- Function File:  box (H, ...)
     Control the display of a border around the plot.  The argument may
     be either `"on"' or `"off"'.  If it is omitted, the current box
     state is toggled.

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

 -- Function File:  grid (ARG)
 -- Function File:  grid ("minor", ARG2)
 -- Function File:  grid (HAX, ...)
     Force the display of a grid on the plot.  The argument may be
     either `"on"', or `"off"'.  If it is omitted, the current grid
     state is toggled.

     If ARG is `"minor"' then the minor grid is toggled.  When using a
     minor grid a second argument ARG2 is allowed, which can be either
     `"on"' or `"off"' to explicitly set the state of the minor grid.

     If the first argument is an axis handle, HAX, operate on the
     specified axis object.

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

 -- Function File:  colorbar (S)
 -- Function File:  colorbar ("peer", H, ...)
     Adds a colorbar to the current axes.  Valid values for S are

    "EastOutside"
          Place the colorbar outside the plot to the right.  This is
          the default.

    "East"
          Place the colorbar inside the plot to the right.

    "WestOutside"
          Place the colorbar outside the plot to the left.

    "West"
          Place the colorbar inside the plot to the left.

    "NorthOutside"
          Place the colorbar above the plot.

    "North"
          Place the colorbar at the top of the plot.

    "SouthOutside"
          Place the colorbar under the plot.

    "South"
          Place the colorbar at the bottom of the plot.

    "Off", "None"
          Remove any existing colorbar from the plot.

     If the argument "peer" is given, then the following argument is
     treated as the axes handle on which to add the colorbar.


File: octave.info,  Node: Multiple Plots on One Page,  Next: Multiple Plot Windows,  Prev: Plot Annotations,  Up: High-Level Plotting

15.2.4 Multiple Plots on One Page
---------------------------------

Octave can display more than one plot in a single figure.  The simplest
way to do this is to use the `subplot' function to divide the plot area
into a series of subplot windows that are indexed by an integer.  For
example,

     subplot (2, 1, 1)
     fplot (@sin, [-10, 10]);
     subplot (2, 1, 2)
     fplot (@cos, [-10, 10]);

creates a figure with two separate axes, one displaying a sine wave and
the other a cosine wave.  The first call to subplot divides the figure
into two plotting areas (two rows and one column) and makes the first
plot area active.  The grid of plot areas created by `subplot' is
numbered in column-major order (top to bottom, left to right).

 -- Function File:  subplot (ROWS, COLS, INDEX)
 -- Function File:  subplot (RCN)
     Set up a plot grid with ROWS by COLS subwindows and plot in
     location given by INDEX.

     If only one argument is supplied, then it must be a three digit
     value specifying the location in digits 1 (rows) and 2 (columns)
     and the plot index in digit 3.

     The plot index runs row-wise.  First all the columns in a row are
     filled and then the next row is filled.

     For example, a plot with 2 by 3 grid will have plot indices
     running as follows:

          +-----+-----+-----+
          |  1  |  2  |  3  |
          +-----+-----+-----+
          |  4  |  5  |  6  |
          +-----+-----+-----+

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


File: octave.info,  Node: Multiple Plot Windows,  Next: Printing and Saving Plots,  Prev: Multiple Plots on One Page,  Up: High-Level Plotting

15.2.5 Multiple Plot Windows
----------------------------

You can open multiple plot windows using the `figure' function.  For
example,

     figure (1);
     fplot (@sin, [-10, 10]);
     figure (2);
     fplot (@cos, [-10, 10]);

creates two figures, with the first displaying a sine wave and the
second a cosine wave.  Figure numbers must be positive integers.

 -- Function File:  figure (N)
 -- Function File:  figure (N, PROPERTY, VALUE, ...)
     Set the current plot window to plot window N.  If no arguments are
     specified, the next available window number is chosen.

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

15.2.6 Use of `axis',  `line', and `patch' functions
----------------------------------------------------

You can create axes, line, and patch objects directly using the `axes',
`line', and `patch' functions.  These objects become children of the
current axes object.

 -- Function File:  axes ()
 -- Function File:  axes (PROPERTY, VALUE, ...)
 -- Function File:  axes (H)
     Create an axes object and return a handle to it.

 -- Function File:  line ()
 -- Function File:  line (X, Y)
 -- Function File:  line (X, Y, Z)
 -- Function File:  line (X, Y, Z, PROPERTY, VALUE, ...)
     Create line object from X and Y and insert in current axes object.
     Return a handle (or vector of handles) to the line objects created.

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

 -- Function File:  patch ()
 -- Function File:  patch (X, Y, C)
 -- Function File:  patch (X, Y, Z, C)
 -- Function File:  patch (FV)
 -- Function File:  patch ('Faces', F, 'Vertices', V, ...)
 -- Function File:  patch (..., PROP, VAL)
 -- Function File:  patch (H, ...)
 -- Function File: H = patch (...)
     Create patch object from X and Y with color C and insert in the
     current axes object.  Return handle to patch object.

     For a uniform colored patch, C can be given as an RGB vector,
     scalar value referring to the current colormap, or string value
     (for example, "r" or "red").

     If passed a structure FV contain the fields "vertices", "faces"
     and optionally "facevertexcdata", create the patch based on these
     properties.

 -- Function File:  fill (X, Y, C)
 -- Function File:  fill (X1, Y1, C1, X2, Y2, C2)
 -- Function File:  fill (..., PROP, VAL)
 -- Function File:  fill (H, ...)
 -- Function File: H = fill (...)
     Create one or more filled patch objects, returning a patch object
     for each.

 -- Function File:  surface (X, Y, Z, C)
 -- Function File:  surface (X, Y, Z)
 -- Function File:  surface (Z, C)
 -- Function File:  surface (Z)
 -- Function File:  surface (..., PROP, VAL)
 -- Function File:  surface (H, ...)
 -- Function File: H = surface (...)
     Plot a surface graphic object given matrices X, and Y from
     `meshgrid' and a matrix Z corresponding to the X and Y coordinates
     of the surface.  If X and Y are vectors, then a typical vertex is
     (X(j), Y(i), Z(i,j)).  Thus, columns of Z correspond to different
     X values and rows of Z correspond to different Y values.  If X and
     Y are missing, they are constructed from size of the matrix Z.

     Any additional properties passed are assigned to the surface.

     *See also:* *note surf: doc-surf, *note mesh: doc-mesh, *note
     patch: doc-patch, *note line: doc-line.

15.2.7 Manipulation of plot windows
-----------------------------------

By default, Octave refreshes the plot window when a prompt is printed,
or when waiting for input.  The `drawnow' function is used to cause a
plot window to be updated.

 -- Built-in Function:  drawnow ()
 -- Built-in Function:  drawnow ("expose")
 -- Built-in Function:  drawnow (TERM, FILE, MONO, DEBUG_FILE)
     Update figure windows and their children.  The event queue is
     flushed and any callbacks generated are executed.  With the
     optional argument `"expose"', only graphic objects are updated and
     no other events or callbacks are processed.  The third calling
     form of `drawnow' is for debugging and is undocumented.

   Only figures that are modified will be updated.  The `refresh'
function can also be used to force an update of the current figure,
even if it is not modified.

 -- Function File:  refresh ()
 -- Function File:  refresh (H)
     Refresh a figure, forcing it to be redrawn.  Called without an
     argument the current figure is redrawn, otherwise the figure
     pointed to by H is redrawn.

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

   Normally, high-level plot functions like `plot' or `mesh' call
`newplot' to initialize the state of the current axes so that the next
plot is drawn in a blank window with default property settings.  To
have two plots superimposed over one another, use the `hold' function.
For example,

     hold on;
     x = -10:0.1:10;
     plot (x, sin (x));
     plot (x, cos (x));
     hold off;

displays sine and cosine waves on the same axes.  If the hold state is
off, consecutive plotting commands like this will only display the last
plot.

 -- Function File:  newplot ()
     Prepare graphics engine to produce a new plot.  This function is
     called at the beginning of all high-level plotting functions.  It
     is not normally required in user programs.

 -- Command:  hold
 -- Command:  hold STATE
 -- Function File:  hold (HAX, ...)
     Toggle or set the 'hold' state of the plotting engine which
     determines whether new graphic objects are added to the plot or
     replace the existing objects.

    `hold on'
          Retain plot data and settings so that subsequent plot
          commands are displayed on a single graph.

    `hold all'
          Retain plot line color, line style, data and settings so that
          subsequent plot commands are displayed on a single graph with
          the next line color and style.

    `hold off'
          Clear plot and restore default graphics settings before each
          new plot command.  (default).

    `hold'
          Toggle the current 'hold' state.

     When given the additional argument HAX, the hold state is modified
     only for the given axis handle.

     To query the current 'hold' state use the `ishold' function.

     *See also:* *note ishold: doc-ishold, *note cla: doc-cla, *note
     newplot: doc-newplot, *note clf: doc-clf.

 -- Command:  ishold
     Return true if the next plot will be added to the current plot, or
     false if the plot device will be cleared before drawing the next
     plot.

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

   To clear the current figure, call the `clf' function.  To clear the
current axis, call the `cla' function.  To bring the current figure to
the top of the window stack, call the `shg' function.  To delete a
graphics object, call `delete' on its index.  To close the figure
window, call the `close' function.

 -- Function File:  clf ()
 -- Function File:  clf ("reset")
 -- Function File:  clf (HFIG)
 -- Function File:  clf (HFIG, "reset")
     Clear the current figure window.  `clf' operates by deleting child
     graphics objects with visible handles (`handlevisibility' = on).
     If HFIG is specified operate on it instead of the current figure.
     If the optional argument `"reset"' is specified, all objects
     including those with hidden handles are deleted.

     *See also:* *note cla: doc-cla, *note close: doc-close, *note
     delete: doc-delete.

 -- Function File:  cla ()
 -- Function File:  cla ("reset")
 -- Function File:  cla (HAX)
 -- Function File:  cla (HAX, "reset")
     Delete the children of the current axes with visible handles.  If
     HAX is specified and is an axes object handle, operate on it
     instead of the current axes.  If the optional argument `"reset"'
     is specified, also delete the children with hidden handles.

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

 -- Command:  shg
     Show the graph window.  Currently, this is the same as executing
     `drawnow'.

     *See also:* *note drawnow: doc-drawnow, *note figure: doc-figure.

 -- Function File:  delete (FILE)
 -- Function File:  delete (HANDLE)
     Delete the named file or graphics handle.

     Deleting graphics objects is the proper way to remove features
     from a plot without clearing the entire figure.

     *See also:* *note clf: doc-clf, *note cla: doc-cla.

 -- Command:  close
 -- Command:  close (N)
 -- Command:  close all
 -- Command:  close all hidden
     Close figure window(s) by calling the function specified by the
     `"closerequestfcn"' property for each figure.  By default, the
     function `closereq' is used.

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

 -- Function File:  closereq ()
     Close the current figure and delete all graphics objects associated
     with it.

     *See also:* *note close: doc-close, *note delete: doc-delete.

15.2.8 Use of the `interpreter' Property
----------------------------------------

All text objects, including titles, labels, legends, and text, include
the property 'interpreter', this property determines the manner in which
special control sequences in the text are rendered.  If the interpreter
is set to 'none', then no rendering occurs.  At this point the 'latex'
option is not implemented and so the 'latex' interpreter also does not
interpret the text.

   The 'tex' option implements a subset of TeX functionality in the
rendering of the text.  This allows the insertion of special characters
such as Greek or mathematical symbols within the text.  The special
characters are also inserted with a code starting with the back-slash
(\) character, as in the table *note tab:extended::.

   In addition, the formatting of the text can be changed within the
string with the codes

               \bf            Bold font                                   
               \it            Italic font                                 
               \sl            Oblique Font                                
               \rm            Normal font                                 

   These are be used in conjunction with the { and } characters to limit
the change in the font to part of the string.  For example,

     xlabel ('{\bf H} = a {\bf V}')

where the character 'a' will not appear in a bold font.  Note that to
avoid having Octave interpret the backslash characters in the strings,
the strings should be in single quotes.

   It is also possible to change the fontname and size within the text

        \fontname{FONTNAME}           Specify the font to use                     
        \fontsize{SIZE}               Specify the size of the font to use         

   Finally, the superscript and subscripting can be controlled with the
'^' and '_' characters.  If the '^' or '_' is followed by a { character,
then all of the block surrounded by the { } pair is super- or
sub-scripted.  Without the { } pair, only the character immediately
following the '^' or '_' is super- or sub-scripted.

          \forall            \exists            \ni                
          \cong              \Delta             \Phi               
          \Gamma             \vartheta          \Lambda            
          \Pi                \Theta             \Sigma             
          \varsigma          \Omega             \Xi                
          \Psi               \perp              \alpha             
          \beta              \chi               \delta             
          \epsilon           \phi               \gamma             
          \eta               \iota              \varphi            
          \kappa             \lambda            \mu                
          \nu                \o                 \pi                
          \theta             \rho               \sigma             
          \tau               \upsilon           \varpi             
          \omega             \xi                \psi               
          \zeta              \sim               \Upsilon           
          \prime             \leq               \infty             
          \clubsuit          \diamondsuit       \heartsuit         
          \spadesuit         \leftrightarrow    \leftarrow         
          \uparrow           \rightarrow        \downarrow         
          \circ              \pm                \geq               
          \times             \propto            \partial           
          \bullet            \div               \neq               
          \equiv             \approx            \ldots             
          \mid               \aleph             \Im                
          \Re                \wp                \otimes            
          \oplus             \oslash            \cap               
          \cup               \supset            \supseteq          
          \subset            \subseteq          \in                
          \notin             \angle             \bigrightriangledown
          \langle            \rangle            \nabla             
          \prod              \surd              \cdot              
          \neg               \wedge             \vee               
          \Leftrightarrow    \Leftarrow         \Uparrow           
          \Rightarrow        \Downarrow         \diamond           
          \copyright         \lfloor            \lceil             
          \rfloor            \rceil             \int               

Table 15.1: Available special characters in TeX mode

   A complete example showing the capabilities of the extended text is

     x = 0:0.01:3;
     plot(x,erf(x));
     hold on;
     plot(x,x,"r");
     axis([0, 3, 0, 1]);
     text(0.65, 0.6175, strcat('\leftarrow x = {2/\surd\pi',
     ' {\fontsize{16}\int_{\fontsize{8}0}^{\fontsize{8}x}}',
     ' e^{-t^2} dt} = 0.6175'))

