   Copyright (C) 1996, 1997 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.

Assignment Expressions
======================

   An "assignment" is an expression that stores a new value into a
variable.  For example, the following expression assigns the value 1 to
the variable `z':

     z = 1

   After this expression is executed, the variable `z' has the value 1.
Whatever old value `z' had before the assignment is forgotten.  The `='
sign is called an "assignment operator".

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

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

(This also illustrates concatenation of strings.)

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

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

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

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

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

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

     a(:, 2) = 5

sets all the elements in the second column of `a' to 5.

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

     A (3, :) = []

deletes the third row of A, and the assignment

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

deletes the first, third, and fifth columns.

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

     x = y = z = 0

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

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

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

that is exactly equivalent to

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

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

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

is equivalent to the expression above, except that the value of the
variable `d' is left unchanged, and the expression

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

is equivalent to

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

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

 - print_rhs_assign_val:
     If the value of this variable is non-zero, Octave will print the
     value of the right hand side of assignment expressions instead of
     the value of the left hand side (after the assignment).

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.

   It is not currently possible to increment index expressions.  For
example, you might expect that the expression `V(4)++' would increment
the fourth element of the vector V, but instead it results in a parse
error.  This problem may be fixed in a future release of Octave.

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'
     `^', `**', `.^', `.**'.

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, or use a string as the name
of a function to call.  The `eval' and `feval' functions allow you to
do just that, and are necessary in order to evaluate commands that are
not known until run time, or to write functions that will need to call
user-supplied functions.

 - Built-in Function:  eval (TRY, CATCH)
     Parse the string TRY and evaluate it as if it were an Octave
     program, returning the last value computed.  If that fails,
     evaluate the string CATCH.  The string TRY is evaluated in the
     current context, so any results remain available after `eval'
     returns.  For example,

          eval ("a = 13")
               -| a = 13
               => 13

     In this case, the value of the evaluated expression is printed and
     it is also returned returned from `eval'.  Just as with any other
     expression, you can turn printing off by ending the expression in a
     semicolon.  For example,

          eval ("a = 13;")
               => 13

     In this example, the variable `a' has been given the value 13, but
     the value of the expression is not printed.  You can also turn off
     automatic printing for all expressions executed by `eval' using the
     variable `default_eval_print_flag'.

 - Built-in Variable: default_eval_print_flag
     If the value of this variable is nonzero, Octave prints the
     results of commands executed by `eval' that do not end with
     semicolons.  If it is zero, automatic printing is suppressed.  The
     default value is 1.

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

   Here 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.  See Predicates for Numeric Objects,
for example, for a list of predicates for numeric objects,
and Status of Variables, for a description of the `exist'
function.

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

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 _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.  See
Functions and Scripts.

 - Built-in Variable: warn_assign_as_truth_value
     If the value of `warn_assign_as_truth_value' is nonzero, 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
     setting `warn_assign_as_truth_value' to 0, 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.

     The default value of `warn_assign_as_truth_value' is 1.

The `switch' Statement
======================

   The `switch' statement was introduced in Octave 2.0.5.  It should be
considered experimental, and details of the implementation may change
slightly in future versions of Octave.  If you have comments or would
like to share your experiences in trying to use this new command in real
programs, please send them to <octave-maintainers@bevo.che.wisc.edu>.
(But if you think you've found a bug, please report it to
<bug-octave@bevo.che.wisc.edu>.

   The general form of the `switch' statement is

     switch EXPRESSION
       case LABEL
         COMMAND_LIST
       case LABEL
         COMMAND_LIST
       ...

       otherwise
         COMMAND_LIST
     endswitch

   * The identifiers `switch', `case', `otherwise', and `endswitch' are
     now keywords.

   * The LABEL may be any expression.

   * Duplicate LABEL values are not detected.  The COMMAND_LIST
     corresponding to the first match will be executed.

   * You must have at least one `case LABEL COMMAND_LIST' clause.

   * The `otherwise COMMAND_LIST' clause is optional.

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

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

   * The implementation is simple-minded and currently offers no real
     performance improvement over an equivalent `if' block, even if all
     the labels are integer constants.  Perhaps a future variation on
     this could detect all constant integer labels and improve
     performance by using a jump table.

 - Built-in Variable: warn_variable_switch_label
     If the value of this variable is nonzero, Octave will print a
     warning if a switch label is not a constant or constant expression

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

   See The if Statement, for a description of the variable
`warn_assign_as_truth_value'.

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

   See The if Statement, for a description of the variable
`warn_assign_as_truth_value'.

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

   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.

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

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

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

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 built-in variable `do_fortran_indexing' even
if an error occurs while performing the indexing operation.

     save_do_fortran_indexing = do_fortran_indexing;
     unwind_protect
       do_fortran_indexing = 1;
       elt = a (idx)
     unwind_protect_cleanup
       do_fortran_indexing = save_do_fortran_indexing;
     end_unwind_protect

   Without `unwind_protect', the value of DO_FORTRAN_INDEXING would not
be restored if an error occurs while performing the indexing operation
because evaluation would stop at the point of the error and the
statement to restore the value would not be executed.

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 access
the text of the message that would have been printed in the builtin
constant `__error_text__'.  This is the same as `eval (TRY, CATCH)'
(which may now also use `__error_text__') but it is more efficient
since the commands do not need to be parsed each time the TRY and CATCH
statements are evaluated.  See Error Handling, for more information
about the `__error_text__' variable.

   Octave's TRY block is a very limited variation on the Lisp
condition-case form (limited because it cannot handle different classes
of errors separately).  Perhaps at some point Octave can have some sort
of classification of errors and try-catch can be improved to be as
powerful as condition-case in Lisp.

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

Functions and Script Files
**************************

   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.

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 (see Input and Output) simply tells
Octave to print the string `"\a"'.  The special character `\a' stands
for the alert character (ASCII 7).  See 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
`beep' 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.
See 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: `retval' undefined near line 1 column 10
     error: evaluating index expression near line 7, column 1

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.

 - Automatic Variable: nargin
     When a function is called, this local variable is automatically
     initialized to the number of arguments passed to the function.  At
     the top level, `nargin' holds the number of command line arguments
     that were passed to Octave.

 - Built-in Variable: silent_functions
     If the value of `silent_functions' is nonzero, internal output
     from a function is suppressed.  Otherwise, the results of
     expressions within a function body that are not terminated with a
     semicolon will have their values printed.  The default value is 0.

     For example, if the function

          function f ()
            2 + 2
          endfunction

     is executed, Octave will either print `ans = 4' or nothing
     depending on the value of `silent_functions'.

 - Built-in Variable: warn_missing_semicolon
     If the value of this variable is nonzero, Octave will warn when
     statements in function definitions don't end in semicolons.  The
     default value is 0.

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

provided that the built-in variable `define_all_return_values' is
nonzero and the value of `default_return_value' is `[]'.  See Summary of Built-in Variables.

 - Automatic Variable: nargout
     When a function is called, this local variable is automatically
     initialized to the number of arguments expected to be returned.
     For example,

          f ()

     will result in `nargout' being set to 0 inside the function `f' and

          [s, t] = f ()

     will result in `nargout' being set to 2 inside the function `f'.

     At the top level, `nargout' is undefined.

 - Built-in Variable: default_return_value
     The value given to otherwise uninitialized return values if
     `define_all_return_values' is nonzero.  The default value is `[]'.

 - Built-in Variable: define_all_return_values
     If the value of `define_all_return_values' is nonzero, Octave will
     substitute the value specified by `default_return_value' for any
     return values that remain undefined when a function returns.  The
     default value is 0.

 - Function File:  nargchk (NARGIN_MIN, NARGIN_MAX, N)
     If N is in the range NARGIN_MIN through NARGIN_MAX inclusive,
     return the empty matrix.  Otherwise, return a message indicating
     whether N is too large or too small.

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

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

   Octave has a real mechanism for handling functions that take an
unspecified number of arguments, so it is not necessary to place an
upper bound on the number of optional arguments that a function can
accept.

   Here is an example of a function that uses the new syntax to print a
header followed by an unspecified number of values:

     function foo (heading, ...)
       disp (heading);
       va_start ();
       ## Pre-decrement to skip `heading' arg.
       while (--nargin)
         disp (va_arg ());
       endwhile
     endfunction

   The ellipsis that marks the variable argument list may only appear
once and must be the last element in the list of arguments.

 - Built-in Function:  va_arg ()
     Return the value of the next available argument and move the
     internal pointer to the next argument.  It is an error to call
     `va_arg' when ther eare no more arguments available, or in a
     function that has not been declared to take a variable number of
     parameters.

 - Built-in Function:  va_start ()
     Position an internal pointer to the first unnamed argument in
     functions that have been declared to accept a variable number of
     arguments.  It is an error to call `va_start' in a function that
     has not been declared to take a variable number of parameters.

   Sometimes it is useful to be able to pass all unnamed arguments to
another function.  The keyword ALL_VA_ARGS makes this very easy to do.
For example,

     function f (...)
       while (nargin--)
         disp (va_arg ())
       endwhile
     endfunction

     function g (...)
       f ("begin", all_va_args, "end")
     endfunction

     g (1, 2, 3)

          -| begin
          -| 1
          -| 2
          -| 3
          -| end

 - Keyword: all_va_args
     This keyword stands for the entire list of optional argument, so
     it is possible to use it more than once within the same function
     without having to call `va_start'.  It can only be used within
     functions that take a variable number of arguments.  It is an
     error to use it in other contexts.

Variable-length Return Lists
============================

   Octave also has a real mechanism for handling functions that return
an unspecified number of values, so it is no longer necessary to place
an upper bound on the number of outputs that a function can produce.

   Here is an example of a function that uses a variable-length return
list to produce N values:

     function [...] = f (n, x)
       for i = 1:n
         vr_val (i * x);
       endfor
     endfunction

     [dos, quatro] = f (2, 2)
          => dos = 2
          => quatro = 4

   As with variable argument lists, the ellipsis that marks the variable
return list may only appear once and must be the last element in the
list of returned values.

 - Built-in Function:  vr_val (X)
     Each time this function is called, it places the value of its
     argument at the end of the list of values to return from the
     current function.  Once `vr_val' has been called, there is no way
     to go back to the beginning of the list and rewrite any of the
     return values.  This function may only be called within functions
     that have been declared to return an unspecified number of output
     arguments.