This is octave.info, produced by makeinfo version 4.8 from
/usr/obj/ports/octave-3.0.5/octave-3.0.5/doc/interpreter/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
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: Commands,  Next: Organization of Functions,  Prev: Function Handles Inline Functions and Anonymous Functions,  Up: Functions and Scripts

11.10 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 like the following example shows

     my_command hello world

which is the same as

     my_command("hello", "world")

   The general form of a command call is

     NAME ARG1 ARG2 ...

which translates directly to

     NAME ("ARG1", "ARG2", ...)

   A function can be used as a command if it accepts string input
arguments.  To do this, the function must be marked as a command, which
can be done with the `mark_as_command' command like this

     mark_as_command name

where `name' is the function to be marked as a command.

   One difficulty of commands occurs when one of the string input
arguments are stored in a variable. Since 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.

 -- Built-in Function:  mark_as_command (NAME)
     Enter NAME into the list of commands.

     *See also:* unmark_command, iscommand.

 -- Built-in Function:  unmark_command (NAME)
     Remove NAME from the list of commands.

     *See also:* mark_as_command, iscommand.

 -- Built-in Function:  iscommand (NAME)
     Return true if NAME is a command style function.  If NAME is
     omitted, return a list of identifiers which are marked as commands
     with `mark_as_command'.

     *See also:* mark_as_command, unmark_command.

 -- Built-in Function:  mark_as_rawcommand (NAME)
     Enter NAME into the list of raw input commands and to the list of
     command style functions.  Raw input commands are like normal
     command style functions, but they receive their input unprocessed
     (ie. strings still contain the quotes and escapes they had when
     input). However, comments and continuations are handled as usual,
     you cannot pass a token starting with a comment character ('#' or
     '%') to your function, and the last token cannot be a continuation
     token ('\' or '...').

     *See also:* unmark_rawcommand, israwcommand, iscommand,
     mark_as_command.

 -- Built-in Function:  unmark_rawcommand (NAME)
     Remove NAME from the list of raw input commands.  Note that this
     does not remove NAME from the list of command style functions.

     *See also:* mark_as_rawcommand, israwcommand, iscommand,
     unmark_command.

 -- Built-in Function:  israwcommand (NAME)
     Return true if NAME is a raw input command function.  If NAME is
     omitted, return a list of identifiers which are marked as raw
     input commands with mark_as_rawcommand.

     *See also:* mark_as_rawcommand, unmark_rawcommand.


File: octave.info,  Node: Organization of Functions,  Prev: Commands,  Up: Functions and Scripts

11.11 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: evaluating index expression near line 1, column 30
          error: evaluating binary operator `||' near line 1, column 27
          error: called from `h'
          error: called from `g'
          error: called from `f'

     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 ()
          -| Invalid call to f.  Correct usage is:
          -|
          -|  -- Function File: f (ARG1)
          -|
          -|
          -|
          -| error: evaluating if command near line 6, column 3
          -| error: called from `f' in file `/home/jwe/octave/f.m'

 -- Loadable Function:  print_usage ()
     Print the usage message for the currently executing function.  The
     `print_usage' function is only intended to work inside a
     user-defined function.

     *See also:* 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:* puts, fputs, printf, 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: ERR = lasterror (ERR)
 -- Built-in Function:  lasterror ('reset')
     Returns or sets 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 can not 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 of 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)
     Reissues 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:* lasterror, lasterr, 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 a 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:* 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 commandline editing and history functions are available in
debug mode. However, one limitation on the debug mode is that commands
entered at the debug prompt are evaluated as strings, rather than being
handled by the Octave parser. This means that all commands in debug
mode must be contained on a single line. That is, it is alright to write

     debug> for i = 1:n, foo(i); endfor

in debug mode. However, writing the above in three lines will not be
correctly evaluated. To leave the debug mode, you should simply type
either `quit', `exit', `return' or `dbcont'.

* Menu:

* Entering Debug Mode::
* Breakpoints::
* Debug Mode::


File: octave.info,  Node: Entering Debug Mode,  Next: Breakpoints,  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: Breakpoints,  Next: Debug Mode,  Prev: Entering Debug Mode,  Up: Debugging

13.2 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 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:* dbclear, dbstatus, dbnext.

Note that breakpoints can not be set in built-in functions (eg. `sin',
etc) or dynamically loaded function (ie. 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:* dbclear, 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 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:* dbstop, dbstatus, dbwhere.

To clear all of the breakpoints in a function the recommended means,
following the above example, is then

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

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

 -- 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 to
     variables.  No value is returned from the `keyboard' function, and
     it continues to prompt for input until the user types `quit', or
     `exit'.

     If `keyboard' is invoked without any arguments, a default prompt of
     `debug> ' is used.

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,  Prev: Breakpoints,  Up: Debugging

13.3 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:* dbclear, dbstatus, dbstop.

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

     *See also:* dbclear, dbstatus, dbstop.

   Debug mode equally allows single line stepping through a function
using the commands `dbstep' and `dbnext'.  These differ slightly in the
way they treat the next executable line if the next line itself is a
function defined in an m-file.  The `dbnext' command will execute the
next line, while staying in the existing function being debugged.  The
`dbstep' command will step in to the new function.


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 most simple functions for data Input and Output
(I/O) are easy to use, but only provides a 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::
* Rational Approximations::


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.

 -- Automatic Variable: ans
     The most recently computed result that was not explicitly assigned
     to a variable.  For example, after the expression

          3^2 + 4^2

     is evaluated, the value returned by `ans' is 25.

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

 -- Command: format options
     Control the format of the output produced by `disp' and Octave's
     normal echoing mechanism.  Valid options are listed in the
     following table.

    `short'
          Octave will try to print numbers with at least 5 significant
          figures within a field that is a maximum of 10 characters
          wide (not counting additional spacing that is added between
          columns of a matrix).

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

    `long'
          Octave will try to print numbers with at least 15 significant
          figures within a field that is a maximum of 20 characters
          wide (not counting additional spacing that is added between
          columns of a matrix).

          As will the `short' format, Octave will switch to an `e'
          format if it is unable to format a matrix so that columns
          line up on the decimal point and all the numbers fit within
          the maximum field width.

    `long e'
    `short e'
          The same as `format long' or `format short' but always display
          output with an `e' format.  For example, with the `short e'
          format, `pi' is displayed as `3.14e+00'.

    `long E'
    `short E'
          The same as `format long e' or `format short e' but always
          display output with an uppercase `E' format.  For example,
          with the `long E' format, `pi' is displayed as
          `3.14159265358979E+00'.

    `long g'
    `short g'
          Choose between normal `long' (or `short') and `long e' (or
          `short e') formats 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

    `long G'
    `short G'
          The same as `format long g' or `format short g' but use an
          uppercase `E' format.  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

    `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 like this `(0.604194,
          0.607088)' instead of like this `0.60419 + 0.60709i'.

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

    `+'
    `+ 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 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 =

               +.-
               -.+

    `native-hex'
          Print the hexadecimal representation 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 `hex' format is
          `400921fb54442d18'.  This format only works for numeric
          values.

    `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 bit format on a workstation which stores 8
          byte real values in IEEE format with the least significant
          byte first.  This format only works for numeric types.

    `bit'
          The same as `native-bit', but always print the most
          significant bits first.

    `compact'
          Remove extra blank space around column number labels.

    `loose'
          Insert blank lines above and below column number labels (this
          is the default).

    `rat'
          Print a rational approximation. That is the values are
          approximated by one small integer divided by another.

     By default, Octave will try to print numbers with at least 5
     significant figures within a field that is a maximum of 10
     characters wide.

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

     If `format' is invoked without any options, the default format
     state is restored.

 -- Built-in Function: VAL = print_answer_id_name ()
 -- Built-in Function: OLD_VAL = print_answer_id_name (NEW_VAL)
     Query or set the internal variable that controls whether variable
     names are printed along with results produced by evaluating an
     expression.

* 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:* more, page_screen_output, page_output_immediately,
     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:* 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:* fopen, 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:* disp, printf, input.

   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,  Next: Rational Approximations,  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 options file V1 V2 ...
     Save the named variables V1, V2, ..., in the file FILE.  The
     special filename `-' can be used to write the output to your
     terminal.  If no variable names are listed, Octave saves all the
     variables in the current scope.  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.

    `-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.  You should use this format only if you
          know that all the values to be saved can be represented in
          single precision.

    `-V7'
    `-v7'
    `-7'
    `-mat7-binary'
          Save the data in MATLAB's v7 binary data format.

    `-V6'
    `-v6'
    `-6'
    `-mat'
    `-mat-binary'
          Save the data in MATLAB's v6 binary data format.

    `-V4'
    `-v4'
    `-4'
    `-mat4-binary'
          Save the data in the binary format written by MATLAB version
          4.

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

    `-float-hdf5'
          Save the data in HDF5 format but only using single precision.
          You should use this format only if you know that all the
          values to be saved can be represented in single precision.

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

     The list of variables to save may include 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.

    `-text'
          Save the data in Octave's text data format.

     Except when using the MATLAB binary data file format, saving global
     variables also saves the global status of the variable, so that if
     it 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.

 -- Command: load options file v1 v2 ...
     Load the named variables V1, V2, ..., from the file FILE.  As with
     `save', you may specify a list of variables and `load' will only
     extract those variables with names that match.  For example, to
     restore the variables saved in the file `data', use the command

          load data

     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.  Since it seems that both of these cases are likely to be
     the result of some sort of error, they will generate warnings.

     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.  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 added in the future).

     Valid options for `load' are listed in the following table.

    `-force'
          The `-force' option is accepted but ignored for backward
          compatibility. Octave now overwrites variables currently in
          memory with the same name as those 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.

    `-mat'
    `-mat-binary'
    `-6'
    `-v6'
    `-7'
    `-v7'
          Force Octave to assume the file is in MATLAB's version 6 or 7
          binary format.

    `-V4'
    `-v4'
    `-4'
    `-mat4-binary'
          Force Octave to assume the file is in the binary format
          written by MATLAB version 4.

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

    `-import'
          The `-import' is accepted but ignored for backward
          compatibility.  Octave can now support multi-dimensional HDF
          data and automatically modifies variable names if they are
          invalid Octave identifiers.

    `-text'
          Force Octave to assume the file is in Octave's text format.

   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"', `"-ascii -zip"'.  The default
     value is `-ascii'.

     *See also:* 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:* strftime.

 -- 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 way much similar 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:* disp.

* 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 unexpected 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 behaviour 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:* octave_core_file_limit, octave_core_file_name,
     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:* crash_dumps_octave_core, octave_core_file_name,
     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:* crash_dumps_octave_core, octave_core_file_name,
     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:* crash_dumps_octave_core, octave_core_file_name,
     octave_core_file_options.


File: octave.info,  Node: Rational Approximations,  Prev: Simple File I/O,  Up: Basic Input and Output

14.1.4 Rational Approximations
------------------------------

 -- Function File: S = rat (X, TOL)
 -- Function File: [N, D] = rat (X, TOL)
     Find a rational approximation to X within tolerance defined by TOL
     using a continued fraction expansion. E.g,

          rat(pi) = 3 + 1/(7 + 1/16) = 355/113
          rat(e) = 3 + 1/(-4 + 1/(2 + 1/(5 + 1/(-2 + 1/(-7)))))
                 = 1457/536

     Called with two arguments returns the numerator and denominator
     separately as two matrices.


*See also:* rats.

 -- Built-in Function:  rats (X, LEN)
     Convert X into a rational approximation represented as a string.
     You can convert the string back into a matrix as follows:

             r = rats(hilb(4));
             x = str2num(r)

     The optional second argument defines the maximum length of the
     string representing the elements of X. By default LEN is 9.

     *See also:* format, rat.


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:* stdout, 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:* stdin, 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:* stdin, 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::
* 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:* fclose, fread, fseek.

 -- Built-in Function:  fclose (FID)
     Closes the specified file.  If successful, `fclose' returns 0,
     otherwise, it returns -1.

     *See also:* fopen, fseek, ftell.


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.

   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:* fread, 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:* fread, fscanf.


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 also:* fprintf, sprintf, 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'.

     *See also:* printf, sprintf, fread, fscanf, fopen, 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:* printf, fprintf, 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 also:* scanf, sscanf, fread, fprintf.

 -- 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:* fscanf, scanf, 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:* fwrite, fopen, 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:* fread, fopen, 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:* tmpfile, tmpnam, 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:* tmpnam, mkstemp, P_tmpdir.

 -- 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:* tmpfile, mkstemp, 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:* fread, fopen, fclose.

 -- Built-in Function:  ferror (FID)
     Return 1 if an error condition has been encountered for a given
     file 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.

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

* Plotting Basics::
* Advanced Plotting::


File: octave.info,  Node: Plotting Basics,  Next: Advanced Plotting,  Up: Plotting

15.1 Plotting Basics
====================

Octave makes it easy to create many different types of two- and
three-dimensional plots using a few high-level functions.

   If you need finer control over graphics, see *Note Advanced
Plotting::.

* Menu:

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


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

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

   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:  plot (Y)
 -- Function File:  plot (X, Y)
 -- Function File:  plot (X, Y, PROPERTY, VALUE, ...)
 -- Function File:  plot (X, Y, FMT)
 -- Function File:  plot (H, ...)
     Produces 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.

    `L'
          Set steps 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.

     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:* semilogx, semilogy, loglog, polar, mesh, contour, bar,
     stairs, errorbar, xlabel, ylabel, title, print.

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

   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 (ARGS)
     Produce a two-dimensional plot using a log scale for the X axis.
     See the description of `plot' for a description of the arguments
     that `semilogx' will accept.

     *See also:* plot, semilogy, loglog.

 -- Function File:  semilogy (ARGS)
     Produce a two-dimensional plot using a log scale for the Y axis.
     See the description of `plot' for a description of the arguments
     that `semilogy' will accept.

     *See also:* plot, semilogx, loglog.

 -- Function File:  loglog (ARGS)
     Produce a two-dimensional plot using log scales for both axes.  See
     the description of `plot' for a description of the arguments that
     `loglog' will accept.

     *See also:* plot, semilogx, 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, 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 patch object.
     Whereas the option 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:* barh, 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 patch object.
     Whereas the option 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:* bar, plot.

 -- Function File:  hist (Y, X, NORM)
     Produce histogram counts or plots.

     With one vector input argument, 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, plot a
     hystogram where each bin contains a bar per input column.

     Given a second scalar argument, use that as the number of bins.

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

     If third argument is provided, the histogram is normalised 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.

     *See also:* bar.

 -- Function File:  stairs (X, Y)
     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 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:* plot, semilogx, semilogy, loglog, polar, mesh, contour,
     bar, xlabel, ylabel, title.

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

     For example,
          x = 1:10;
          stem (x);
     plots 10 stems with heights from 1 to 10;

          x = 1:10;
          y = ones (1, length (x))*2.*x;
          stem (x, y);
     plots 10 stems with heights from 2 to 20;

          x = 1:10;
          y = ones (size (x))*2.*x;
          h = stem (x, y, "b");
     plots 10 bars with heights from 2 to 20 (the color is blue, and H
     is a 2-by-10 array of handles in which the first row holds the
     line handles and the second row holds the marker handles);

          x = 1:10;
          y = ones (size (x))*2.*x;
          h = stem (x, y, "-.k");
     plots 10 stems with heights from 2 to 20 (the color is black, line
     style is `"-."', and H is a 2-by-10 array of handles in which the
     first row holds the line handles and the second row holds the
     marker handles);

          x = 1:10;
          y = ones (size (x))*2.*x;
          h = stem (x, y, "-.k.");
     plots 10 stems with heights from 2 to 20 (the color is black, line
     style is `"-."' and the marker style is `"."', and H is a 2-by-10
     array of handles in which the first row holds the line handles and
     the second row holds the marker handles);

          x = 1:10;
          y = ones (size (x))*2.*x;
          h = stem (x, y, "fill");
     plots 10 stems with heights from 2 to 20 (the color is rgb-triple
     defined, the line style is `"-"', the marker style is `"o"', and H
     is a 2-by-10 array of handles in which the first row holds the
     line handles and the second row holds the marker handles).

     Color definitions with rgb-triples are not valid!

     *See also:* bar, barh, plot.

   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:* contourc, patch, 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 ommited 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:* contour, contourc, 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:* contour.

   The `errorbar', `semilogxerr', `semilogyerr', and `loglogerr'
functions produces 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 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:* semilogxerr, semilogyerr, loglogerr.

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

          semilogxerr (X, Y, EY, FMT)

     which produces a semi-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:* errorbar, loglogerr semilogyerr.

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

          semilogyerr (X, Y, EY, FMT)

     which produces a semi-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:* errorbar, loglogerr 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:* errorbar, semilogxerr, 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, FMT)
     Make a two-dimensional plot given the polar coordinates THETA and
     RHO.

     The optional third argument specifies the line type.

     *See also:* plot.

 -- Function File:  pie (Y)
 -- Function File:  pie (Y, 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:* bar, 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 list of handles to the the
     parts of the vector field (body, arrow and marker).

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


     *See also:* plot.

 -- 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:* caxis, contour, meshgrid, imagesc, 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 the list
     of patch objects.

     *See also:* plot, patch.

   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 (LIMITS)
     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 ("labely", "tic");

     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 (not implemented).

     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.


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

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

     *See also:* meshgrid, contour.

 -- 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:* meshgrid, mesh, 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:* mesh, meshc, surf.

 -- Function File:  surf (X, Y, Z)
     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.

     *See also:* mesh, surface.

 -- 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:* meshgrid, surf, contour.

 -- 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:* mesh, 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 ith output argument contains the elements
     of the vector Xi repeated over all dimensions different from the
     ith 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:* 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:* plot.

 -- Function File:  view (AZIMUTH, ELEVATION)
 -- Function File:  view (DIMS)
 -- Function File: [AZIMUTH, ELEVATION] = view ()
     Set or get the viewpoint for the current axes.

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


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

15.1.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 (TITLE)
     Create a title object and return a handle to it.

 -- Function File:  legend (ST1, ST2, ...)
 -- Function File:  legend (ST1, ST2, ..., "location", POS)
 -- Function File:  legend (MATSTR)
 -- Function File:  legend (MATSTR, "location", POS)
 -- Function File:  legend (CELL)
 -- Function File:  legend (CELL, "location", POS)
 -- Function File:  legend ('FUNC')
     Display a legend for 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.  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

     Some specific functions are directly available using FUNC:

    "show"
          Show legends from the plot

    "hide"
    "off"
          Hide legends from the plot

    "boxon"
          Draw a box around legends

    "boxoff"
          Withdraw the box around legends

    "left"
          Text is to the left of the keys

    "right"
          Text is to the right of the keys

 -- 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:  ylabel (STRING)
 -- Function File:  zlabel (STRING)
 -- Function File:  xlabel (H, STRING)
     Specify x, y, and z axis labels for the current figure. If H is
     specified then label the axis defined by H.

     *See also:* plot, semilogx, semilogy, loglog, polar, mesh, contour,
     bar, stairs,  ylabel, title.

 -- 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:* 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:* 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: Plotting Basics

15.1.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 COLS by ROWS 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:* plot.


File: octave.info,  Node: Multiple Plot Windows,  Next: Printing Plots,  Prev: Multiple Plots on One Page,  Up: Plotting Basics

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


File: octave.info,  Node: Printing Plots,  Next: Test Plotting Functions,  Prev: Multiple Plot Windows,  Up: Plotting Basics

15.1.6 Printing Plots
---------------------

The `print' command allows you to save plots in a variety of formats.
For example,

     print -deps foo.eps

writes the current figure to an encapsulated PostScript file called
`foo.eps'.

 -- Function File:  print (FILENAME, OPTIONS)
     Print a graph, or save it to a file

     FILENAME defines the file name of the output file. If no filename
     is specified, output is sent to the printer.

     OPTIONS:
    `-PPRINTER'
          Set the PRINTER name to which the graph is sent if no
          FILENAME is specified.

    `-color'
    `-mono'
          Monochrome or colour lines.

    `-solid'
    `-dashed'
          Solid or dashed lines.

    `-portrait'
    `-landscape'
          Plot orientation, as returned by "orient".

    `-dDEVICE'
          Output device, where DEVICE is one of:
         `ps'
         `ps2'
         `psc'
         `psc2'
               Postscript (level 1 and 2, mono and color)

         `eps'
         `eps2'
         `epsc'
         `epsc2'
               Encapsulated postscript (level 1 and 2, mono and color)

         `tex'
         `epslatex'
         `epslatexstandalone'
         `pstex'
         `pslatex'
               Generate a LaTeX (or TeX) file for labels, and eps/ps for
                  graphics.  The file produced by `epslatexstandalone'
               can be     processed directly by LaTeX.  The other
               formats are intended to     be included in a LaTeX (or
               TeX) document.  The `tex' device     is the same as the
               `epslatex' device.

         `ill'
         `aifm'
               Adobe Illustrator

         `cdr'
         `corel'
               CorelDraw

         `dxf'
               AutoCAD

         `emf'
               Microsoft Enhanced Metafile

         `fig'
               XFig.  If this format is selected the additional options
               `-textspecial' or `-textnormal' can be used to control
                whether the special flag should be set for the text in
               the figure     (default is `-textnormal').

         `hpgl'
               HP plotter language

         `mf'
               Metafont

         `png'
               Portable network graphics

         `jpg'
         `jpeg'
               JPEG image

         `gif'
               GIF image

         `pbm'
               PBMplus

         `svg'
               Scalable vector graphics

         `pdf'
               Portable document format

          Other devices are supported by "convert" from ImageMagick.
          Type   system("convert") to see what formats are available.

          If the device is omitted, it is inferred from the file
          extension,   or if there is no filename it is sent to the
          printer as postscript.

    `-SXSIZE,YSIZE'
          Plot size in pixels for PNG and SVG.  If using the command
          form of   the print function, you must quote the XSIZE,YSIZE
          option.  For example, by writing `"-S640,480"'.

    `-FFONTNAME'
    `-FFONTNAME:SIZE'
    `-F:SIZE'
          FONTNAME set the postscript font (for use with postscript,
          aifm, corel and fig). By default, 'Helvetica' is set for
          PS/Aifm,   and 'SwitzerlandLight' for Corel. It can also be
          'Times-Roman'.  SIZE is given in points. FONTNAME is ignored
          for the   fig device.

     The filename and options can be given in any order.

 -- Function File:  orient (ORIENTATION)
     Set the default print orientation.  Valid values for ORIENTATION
     include `"landscape"' and `"portrait"'.  If called with no
     arguments, return the default print orientation.


File: octave.info,  Node: Test Plotting Functions,  Prev: Printing Plots,  Up: Plotting Basics

15.1.7 Test Plotting Functions
------------------------------

The functions `sombrero' and `peaks' provide a way to check that
plotting is working.  Typing either `sombrero' or `peaks' at the Octave
prompt should display a three dimensional plot.

 -- Function File:  sombrero (N)
     Produce the familiar three-dimensional sombrero plot using N grid
     lines.  If N is omitted, a value of 41 is assumed.

     The function plotted is

          z = sin (sqrt (x^2 + y^2)) / (sqrt (x^2 + y^2))


     *See also:* surf, meshgrid, mesh.

 -- Function File:  peaks ()
 -- Function File:  peaks (N)
 -- Function File:  peaks (X, Y)
 -- Function File: Z = peaks (...)
 -- Function File: [X, Y, Z] = peaks (...)
     Generate a function with lots of local maxima and minima. The
     function has the form


     f(x,y) = 3*(1-x)^2*exp(-x^2 - (y+1)^2) ...
              - 10*(x/5 - x^3 - y^5)*exp(-x^2-y^2) ...
              - 1/3*exp(-(x+1)^2 - y^2)

     Called without a return argument, `peaks' plots the surface of the
     above function using `mesh'. If N is a scalar, the `peaks' returns
     the values of the above function on a N-by-N mesh over the range
     `[-3,3]'. The default value for N is 49.

     If N is a vector, then it represents the X and Y values of the
     grid on which to calculate the above function. The X and Y values
     can be specified separately.

     *See also:* surf, mesh, meshgrid.


File: octave.info,  Node: Advanced Plotting,  Prev: Plotting Basics,  Up: Plotting

15.2 Advanced Plotting
======================

* Menu:

* Graphics Objects::
* Graphics Object Properties::
* Managing Default Properties::
* Colors::
* Line Styles::
* Marker Styles::
* Interaction with gnuplot::


File: octave.info,  Node: Graphics Objects,  Next: Graphics Object Properties,  Up: Advanced Plotting

15.2.1 Graphics Objects
-----------------------

Plots in Octave are constructed from the following "graphics objects".
Each graphics object has a set of properties that define its appearance
and may also contain links to other graphics objects.  Graphics objects
are only referenced by a numeric index, or "handle".

root figure
     The parent of all figure objects.  The index for the root figure is
     defined to be 0.

figure
     A figure window.

axes
     An set of axes.  This object is a child of a figure object and may
     be a parent of line, text, image, patch, or surface objects.

line
     A line in two or three dimensions.

text
     Text annotations.

image
     A bitmap image.

patch
     A filled polygon, currently limited to two dimensions.

surface
     A three-dimensional surface.

   To determine whether an object is a graphics object index or a figure
index, use the functions `ishandle' and `isfigure'.

 -- Built-in Function:  ishandle (H)
     Return true if H is a graphics handle and false otherwise.

 -- Function File:  isfigure (H)
     Return true if H is a graphics handle that contains a figure
     object and false otherwise.

   The function `gcf' returns an index to the current figure object, or
creates one if none exists.  Similarly, `gca' returns the current axes
object, or creates one (and its parent figure object) if none exists.

 -- Function File:  gcf ()
     Return the current figure handle.  If a figure does not exist,
     create one and return its handle.  The handle may then be used to
     examine or set properties of the figure.  For example,

          fplot (@sin, [-10, 10]);
          fig = gcf ();
          set (fig, "visible", "off");

     plots a sine wave, finds the handle of the current figure, and then
     makes that figure invisible.  Setting the visible property of the
     figure to `"on"' will cause it to be displayed again.

     *See also:* get, set.

 -- Function File:  gca ()
     Return a handle to the current axis object.  If no axis object
     exists, create one and return its handle.  The handle may then be
     used to examine or set properties of the axes.  For example,

          ax = gca ();
          set (ax, "position", [0.5, 0.5, 0.5, 0.5]);

     creates an empty axes object, then changes its location and size in
     the figure window.

     *See also:* get, set.

   The `get' and `set' functions may be used to examine and set
properties for graphics objects.  For example,

     get (0)
         => ans =
            {
              type = root figure
              currentfigure = [](0x0)
              children = [](0x0)
              visible = on
            }

returns a structure containing all the properties of the root figure.
As with all functions in Octave, the structure is returned by value, so
modifying it will not modify the internal root figure plot object.  To
do that, you must use the `set' function.  Also, note that in this
case, the `currentfigure' property is empty, which indicates that there
is no current figure window.

   The `get' function may also be used to find the value of a single
property.  For example,

     get (gca (), "xlim")
         => [ 0 1 ]

returns the range of the x-axis for the current axes object in the
current figure.

   To set graphics object properties, use the set function.  For
example,

     set (gca (), "xlim", [-10, 10]);

sets the range of the x-axis for the current axes object in the current
figure to `[-10, 10]'.  Additionally, calling set with a graphics
object index as the only argument returns a structure containing the
default values for all the properties for the given object type.  For
example,

     set (gca ())

returns a structure containing the default property values for axes
objects.

 -- Built-in Function:  get (H, P)
     Return the named property P from the graphics handle H.  If P is
     omitted, return the complete property list for H.  If H is a
     vector, return a cell array including the property values or lists
     respectively.

 -- Built-in Function:  set (H, P, V, ...)
     Set the named property value or vector P to the value V for the
     graphics handle H.

 -- Function File: PARENT = ancestor (H, TYPE)
 -- Function File: PARENT = ancestor (H, TYPE, 'toplevel')
     Return the first ancestor of handle object H whose type matches
     TYPE, where TYPE is a character string. If TYPE is a cell array of
     strings, return the first parent whose type matches any of the
     given type strings.

     If the handle object H is of type TYPE, return H.

     If `"toplevel"' is given as a 3rd argument, return the highest
     parent in the object hierarchy that matches the condition, instead
     of the first (nearest) one.

     *See also:* get, set.

   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, C, OPTS)
 -- 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").

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

     *See also:* surf, mesh, patch, line.

   By default, Octave refreshes the plot window when a prompt is
printed, or when waiting for input.  To force an update at other times,
call the `drawnow' function.

 -- Function File:  drawnow ()
     Update and display the current graphics.

     Octave automatically calls drawnow just before printing a prompt,
     when `sleep' or `pause' is called, or while waiting for
     command-line input.

   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, call 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
     should be called at the beginning of all high-level plotting
     functions.

 -- Function File:  hold ARGS
     Tell Octave to `hold' the current data on the plot when executing
     subsequent plotting commands.  This allows you to execute a series
     of plot commands and have all the lines end up on the same figure.
     The default is for each new plot command to clear the plot device
     first.  For example, the command

          hold on

     turns the hold state on.  An argument of `"off"' turns the hold
     state off, and `hold' with no arguments toggles the current hold
     state.

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

   To clear the current figure, call the `clf' function.  To bring it
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")
 -- Function File: HFIG = clf (...)
     Delete the children of the current figure with visible handles.
     If HFIG is specified and is an figure object handle, operate on it
     instead of the current figure.  If the optional argument `"reset"'
     is specified, also delete the figure's children with hidden
     handles.

     *See also:* cla, close, delete.

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

     *See also:* drawnow, figure.

 -- Function File:  delete (FILE)
 -- Function File:  delete (H)
     Delete the named file or figure handle.

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

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

     *See also:* close, delete.


File: octave.info,  Node: Graphics Object Properties,  Next: Managing Default Properties,  Prev: Graphics Objects,  Up: Advanced Plotting

15.2.2 Graphics Object Properties
---------------------------------

* Menu:

* Root Figure Properties::
* Figure Properties::
* Axes Properties::
* Line Properties::
* Text Properties::
* Image Properties::
* Patch Properties::
* Surface Properties::


File: octave.info,  Node: Root Figure Properties,  Next: Figure Properties,  Up: Graphics Object Properties

15.2.2.1 Root Figure Properties
...............................

`currentfigure'
     Index to graphics object for the current figure.



File: octave.info,  Node: Figure Properties,  Next: Axes Properties,  Prev: Root Figure Properties,  Up: Graphics Object Properties

15.2.2.2 Figure Properties
..........................

`nextplot'
     May be one of
    `"new"'

    `"add"'

    `"replace"'

    `"replacechildren"'

`closerequestfcn'
     Handle of function to call when a figure is closed.

`currentaxes'
     Index to graphics object of current axes.

`colormap'
     An N-by-3 matrix containing the color map for the current axes.

`visible'
     Either `"on"' or `"off"' to toggle display of the figure.

`paperorientation'
     Indicates the orientation for printing.  Either `"landscape"' or
     `"portrait"'.


File: octave.info,  Node: Axes Properties,  Next: Line Properties,  Prev: Figure Properties,  Up: Graphics Object Properties

15.2.2.3 Axes Properties
........................

`position'
     A vector specifying the position of the plot, excluding titles,
     axes and legend.  The four elements of the vector are the
     coordinates of the lower left corner and width and height of the
     plot, in units normalized to the width and height of the plot
     window.  For example, `[0.2, 0.3, 0.4, 0.5]' sets the lower left
     corner of the axes at (0.2, 0.3) and the width and height to be
     0.4 and 0.5 respectively.  See also the `outerposition' property.

`title'
     Index of text object for the axes title.

`box'
     Either `"on"' or `"off"' to toggle display of the box around the
     axes.

`key'
     Either `"on"' or `"off"' to toggle display of the legend.  Note
     that this property is not compatible with MATLAB and may be
     removed in a future version of Octave.

`keybox'
     Either `"on"' or `"off"' to toggle display of a box around the
     legend.  Note that this property is not compatible with MATLAB and
     may be removed in a future version of Octave.

`keypos'
     An integer from 1 to 4 specifying the position of the legend.  1
     indicates upper right corner, 2 indicates upper left, 3 indicates
     lower left, and 4 indicates lower right.  Note that this property
     is not compatible with MATLAB and may be removed in a future
     version of Octave.

`dataaspectratio'
     A two-element vector specifying the relative height and width of
     the data displayed in the axes.  Setting `dataaspectratio' to `1,
     2]' causes the length of one unit as displayed on the y axis to be
     the same as the length of 2 units on the x axis.  Setting
     `dataaspectratio' also forces the `dataaspectratiomode' property
     to be set to `"manual"'.

`dataaspectratiomode'
     Either `"manual"' or `"auto"'.

`xlim'
`ylim'
`zlim'
`clim'
     Two-element vectors defining the limits for the x, y, and z axes
     and the Setting one of these properties also forces the
     corresponding mode property to be set to `"manual"'.

`xlimmode'
`ylimmode'
`zlimmode'
`climmode'
     Either `"manual"' or `"auto"'.

`xlabel'
`ylabel'
`zlabel'
     Indices to text objects for the axes labels.

`xgrid'
`ygrid'
`zgrid'
     Either `"on"' or `"off"' to toggle display of grid lines.

`xminorgrid'
`yminorgrid'
`zminorgrid'
     Either `"on"' or `"off"' to toggle display of minor grid lines.

`xtick'
`ytick'
`ztick'
     Setting one of these properties also forces the corresponding mode
     property to be set to `"manual"'.

`xtickmode'
`ytickmode'
`ztickmode'
     Either `"manual"' or `"auto"'.

`xticklabel'
`yticklabel'
`zticklabel'
     Setting one of these properties also forces the corresponding mode
     property to be set to `"manual"'.

`xticklabelmode'
`yticklabelmode'
`zticklabelmode'
     Either `"manual"' or `"auto"'.

`xscale'
`yscale'
`zscale'
     Either `"linear"' or `"log"'.

`xdir'
`ydir'
`zdir'
     Either `"forward"' or `"reverse"'.

`xaxislocation'
`yaxislocation'
     Either `"top"' or `"bottom"' for the x axis and `"left"' or
     `"right"' for the y axis.

`view'
     A three element vector specifying the view point for
     three-dimensional plots.

`visible'
     Either `"on"' or `"off"' to toggle display of the axes.

`nextplot'
     May be one of
    `"new"'

    `"add"'

    `"replace"'

    `"replacechildren"'

`outerposition'
     A vector specifying the position of the plot, including titles,
     axes and legend.  The four elements of the vector are the
     coordinates of the lower left corner and width and height of the
     plot, in units normalized to the width and height of the plot
     window.  For example, `[0.2, 0.3, 0.4, 0.5]' sets the lower left
     corner of the axes at (0.2, 0.3) and the width and height to be
     0.4 and 0.5 respectively.  See also the `position' property.


File: octave.info,  Node: Line Properties,  Next: Text Properties,  Prev: Axes Properties,  Up: Graphics Object Properties

15.2.2.4 Line Properties
........................

`xdata'
`ydata'
`zdata'
`ldata'
`udata'
`xldata'
`xudata'
     The data to be plotted.  The `ldata' and `udata' elements are for
     errorbars in the y direction, and the `xldata' and `xudata'
     elements are for errorbars in the x direction.

`color'
     The RGB color of the line, or a color name.  *Note Colors::.

`linestyle'
`linewidth'
     *Note Line Styles::.

`marker'

`markeredgecolor'

`markerfacecolor'

`markersize'
     *Note Marker Styles::.

`keylabel'
     The text of the legend entry corresponding to this line.  Note
     that this property is not compatible with MATLAB and may be
     removed in a future version of Octave.


File: octave.info,  Node: Text Properties,  Next: Image Properties,  Prev: Line Properties,  Up: Graphics Object Properties

15.2.2.5 Text Properties
........................

`string'
     The character string contained by the text object.

`units'
     May be `"normalized"' or `"graph"'.

`position'
     The coordinates of the text object.

`rotation'
     The angle of rotation for the displayed text, measured in degrees.

`horizontalalignment'
     May be `"left"', `"center"', or `"right"'.

`color'
     The color of the text.  *Note Colors::.

`fontname'
     The font used for the text.

`fontsize'
     The size of the font, in points to use.

`fontangle'
     Flag whether the font is italic or normal. Valid values are
     'normal', 'italic' and 'oblique'.

`fontweight'
     Flag whether the font is bold, etc. Valid values are 'normal',
     'bold', 'demi' or 'light'.

`interpreter'
     Determines how the text is rendered. Valid values are 'none',
     'tex' or 'latex'.

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


File: octave.info,  Node: Image Properties,  Next: Patch Properties,  Prev: Text Properties,  Up: Graphics Object Properties

15.2.2.6 Image Properties
.........................

`cdata'
     The data for the image.  Each pixel of the image corresponds to an
     element of `cdata'.  The value of an element of `cdata' specifies
     the row-index into the colormap of the axes object containing the
     image.  The color value found in the color map for the given index
     determines the color of the pixel.

`xdata'
`ydata'
     Two-element vectors specifying the range of the x- and y-
     coordinates for the image.


File: octave.info,  Node: Patch Properties,  Next: Surface Properties,  Prev: Image Properties,  Up: Graphics Object Properties

15.2.2.7 Patch Properties
.........................

`cdata'
`xdata'
`ydata'
`zdata'
     Data defining the patch object.

`facecolor'
     The fill color of the patch.  *Note Colors::.

`facealpha'
     A number in the range [0, 1] indicating the transparency of the
     patch.

`edgecolor'
     The color of the line defining the patch.  *Note Colors::.

`linestyle'
`linewidth'
     *Note Line Styles::.

`marker'
`markeredgecolor'
`markerfacecolor'
`markersize'
     *Note Marker Styles::.


File: octave.info,  Node: Surface Properties,  Prev: Patch Properties,  Up: Graphics Object Properties

15.2.2.8 Surface Properties
...........................

`xdata'
`ydata'
`zdata'
     The data determining the surface.  The `xdata' and `ydata'
     elements are vectors and `zdata' must be a matrix.

`keylabel'
     The text of the legend entry corresponding to this surface.  Note
     that this property is not compatible with MATLAB and may be
     removed in a future version of Octave.


File: octave.info,  Node: Managing Default Properties,  Next: Colors,  Prev: Graphics Object Properties,  Up: Advanced Plotting

15.2.3 Managing Default Properties
----------------------------------

Object properties have two classes of default values, "factory
defaults" (the initial values) and "user-defined defaults", which may
override the factory defaults.

   Although default values may be set for any object, they are set in
parent objects and apply to child objects.  For example,

     set (0, "defaultlinecolor", "green");

sets the default line color for all objects.  The rule for constructing
the property name to set a default value is

     default + OBJECT-TYPE + PROPERTY-NAME

   This rule can lead to some strange looking names, for example
`defaultlinelinewidth"' specifies the default `linewidth' property for
`line' objects.

   The example above used the root figure object, 0, so the default
property value will apply to all line objects.  However, default values
are hierarchical, so defaults set in a figure objects override those
set in the root figure object.  Likewise, defaults set in axes objects
override those set in figure or root figure objects.  For example,

     subplot (2, 1, 1);
     set (0, "defaultlinecolor", "red");
     set (1, "defaultlinecolor", "green");
     set (gca (), "defaultlinecolor", "blue");
     line (1:10, rand (1, 10));
     subplot (2, 1, 2);
     line (1:10, rand (1, 10));
     figure (2)
     line (1:10, rand (1, 10));

produces two figures.  The line in first subplot window of the first
figure is blue because it inherits its color from its parent axes
object.  The line in the second subplot window of the first figure is
green because it inherits its color from its parent figure object.  The
line in the second figure window is red because it inherits its color
from the global root figure parent object.

   To remove a user-defined default setting, set the default property to
the value `"remove"'.  For example,

     set (gca (), "defaultlinecolor", "remove");

removes the user-defined default line color setting from the current
axes object.

   Getting the `"default"' property of an object returns a list of
user-defined defaults set for the object.  For example,

     get (gca (), "default");

returns a list of user-defined default values for the current axes
object.

   Factory default values are stored in the root figure object.  The
command

     get (0, "factory");

returns a list of factory defaults.


File: octave.info,  Node: Colors,  Next: Line Styles,  Prev: Managing Default Properties,  Up: Advanced Plotting

15.2.4 Colors
-------------

Colors may be specified as RGB triplets with values ranging from zero to
one, or by name.  Recognized color names include `"blue"', `"black"',
`"cyan"', `"green"', `"magenta"', `"red"', `"white"', and `"yellow"'.


File: octave.info,  Node: Line Styles,  Next: Marker Styles,  Prev: Colors,  Up: Advanced Plotting

15.2.5 Line Styles
------------------

Line styles are specified by the following properties:

`linestyle'
     May be one of
    `"-"'
          Solid lines.

    `"--"'
          Dashed lines.

    `":"'
          Points.

    `"-."'
          A dash-dot line.

`linewidth'
     A number specifying the width of the line.  The default is 1.  A
     value of 2 is twice as wide as the default, etc.


File: octave.info,  Node: Marker Styles,  Next: Interaction with gnuplot,  Prev: Line Styles,  Up: Advanced Plotting

15.2.6 Marker Styles
--------------------

Marker styles are specified by the following properties:
`marker'
     A character indicating a plot marker to be place at each data
     point, or `"none"', meaning no markers should be displayed.

`markeredgecolor'
     The color of the edge around the marker, or `"auto"', meaning that
     the edge color is the same as the face color.  *Note Colors::.

`markerfacecolor'
     The color of the marker, or `"none"' to indicate that the marker
     should not be filled.  *Note Colors::.

`markersize'
     A number specifying the size of the marker.  The default is 1.  A
     value of 2 is twice as large as the default, etc.


File: octave.info,  Node: Interaction with gnuplot,  Prev: Marker Styles,  Up: Advanced Plotting

15.2.7 Interaction with `gnuplot'
---------------------------------

 -- Loadable Function: VAL = gnuplot_binary ()
 -- Loadable Function: OLD_VAL = gnuplot_binary (NEW_VAL)
     Query or set the name of the program invoked by the plot command.
     The default value `"gnuplot"'.  *Note Installation::.

 -- Loadable Function: VAL = gnuplot_use_title_option ()
 -- Loadable Function: OLD_VAL = gnuplot_use_title_option (NEW_VAL)
     If enabled, append `-title "Figure NN"' to the gnuplot command.
     By default, this feature is enabled if the `DISPLAY' environment
     variable is set when Octave starts.

     *This function is obsolete and will be removed from a future
     version of Octave.*


File: octave.info,  Node: Matrix Manipulation,  Next: Arithmetic,  Prev: Plotting,  Up: Top

16 Matrix Manipulation
**********************

There are a number of functions available for checking to see if the
elements of a matrix meet some condition, and for rearranging the
elements of a matrix.  For example, Octave can easily tell you if all
the elements of a matrix are finite, or are less than some specified
value.  Octave can also rotate the elements, extract the upper- or
lower-triangular parts, or sort the columns of a matrix.

* Menu:

* Finding Elements and Checking Conditions::
* Rearranging Matrices::
* Applying a Function to an Array::
* Special Utility Matrices::
* Famous Matrices::


File: octave.info,  Node: Finding Elements and Checking Conditions,  Next: Rearranging Matrices,  Up: Matrix Manipulation

16.1 Finding Elements and Checking Conditions
=============================================

The functions `any' and `all' are useful for determining whether any or
all of the elements of a matrix satisfy some condition.  The `find'
function is also useful in determining which elements of a matrix meet
a specified condition.

 -- Built-in Function:  any (X, DIM)
     For a vector argument, return 1 if any element of the vector is
     nonzero.

     For a matrix argument, return a row vector of ones and zeros with
     each element indicating whether any of the elements of the
     corresponding column of the matrix are nonzero.  For example,

          any (eye (2, 4))
               => [ 1, 1, 0, 0 ]

     If the optional argument DIM is supplied, work along dimension
     DIM.  For example,

          any (eye (2, 4), 2)
               => [ 1; 1 ]

 -- Built-in Function:  all (X, DIM)
     The function `all' behaves like the function `any', except that it
     returns true only if all the elements of a vector, or all the
     elements along dimension DIM of a matrix, are nonzero.

   Since the comparison operators (*note Comparison Ops::) return
matrices of ones and zeros, it is easy to test a matrix for many
things, not just whether the elements are nonzero.  For example,

     all (all (rand (5) < 0.9))
          => 0

tests a random 5 by 5 matrix to see if all of its elements are less
than 0.9.

   Note that in conditional contexts (like the test clause of `if' and
`while' statements) Octave treats the test as if you had typed `all
(all (condition))'.

 -- Mapping Function:  xor (X, Y)
     Return the `exclusive or' of the entries of X and Y.  For boolean
     expressions X and Y, `xor (X, Y)' is true if and only if X or Y is
     true, but not if both X and Y are true.

 -- Function File:  is_duplicate_entry (X)
     Return non-zero if any entries in X are duplicates of one another.

 -- Function File:  diff (X, K, DIM)
     If X is a vector of length N, `diff (X)' is the vector of first
     differences X(2) - X(1), ..., X(n) - X(n-1).

     If X is a matrix, `diff (X)' is the matrix of column differences
     along the first non-singleton dimension.

     The second argument is optional.  If supplied, `diff (X, K)',
     where K is a nonnegative integer, returns the K-th differences. It
     is possible that K is larger than then first non-singleton
     dimension of the matrix. In this case, `diff' continues to take
     the differences along the next non-singleton dimension.

     The dimension along which to take the difference can be explicitly
     stated with the optional variable DIM. In this case the K-th order
     differences are calculated along this dimension.  In the case
     where K exceeds `size (X, DIM)' then an empty matrix is returned.

 -- Mapping Function:  isinf (X)
     Return 1 for elements of X that are infinite and zero otherwise.
     For example,

          isinf ([13, Inf, NA, NaN])
               => [ 0, 1, 0, 0 ]

 -- Mapping Function:  isnan (X)
     Return 1 for elements of X that are NaN values and zero otherwise.
     NA values are also considered NaN values.  For example,

          isnan ([13, Inf, NA, NaN])
               => [ 0, 0, 1, 1 ]

 -- Mapping Function:  finite (X)
     Return 1 for elements of X that are finite values and zero
     otherwise. For example,

          finite ([13, Inf, NA, NaN])
               => [ 1, 0, 0, 0 ]

 -- Loadable Function:  find (X)
 -- Loadable Function:  find (X, N)
 -- Loadable Function:  find (X, N, DIRECTION)
     Return a vector of indices of nonzero elements of a matrix, as a
     row if X is a row or as a column otherwise.  To obtain a single
     index for each matrix element, Octave pretends that the columns of
     a matrix form one long vector (like Fortran arrays are stored).
     For example,

          find (eye (2))
               => [ 1; 4 ]

     If two outputs are requested, `find' returns the row and column
     indices of nonzero elements of a matrix.  For example,

          [i, j] = find (2 * eye (2))
               => i = [ 1; 2 ]
               => j = [ 1; 2 ]

     If three outputs are requested, `find' also returns a vector
     containing the nonzero values.  For example,

          [i, j, v] = find (3 * eye (2))
               => i = [ 1; 2 ]
               => j = [ 1; 2 ]
               => v = [ 3; 3 ]

     If two inputs are given, N indicates the number of elements to
     find from the beginning of the matrix or vector.

     If three inputs are given, DIRECTION should be one of "first" or
     "last" indicating that it should start counting found elements
     from the first or last element.

 -- Function File: [ERR, Y1, ...] = common_size (X1, ...)
     Determine if all input arguments are either scalar or of common
     size.  If so, ERR is zero, and YI is a matrix of the common size
     with all entries equal to XI if this is a scalar or XI otherwise.
     If the inputs cannot be brought to a common size, errorcode is 1,
     and YI is XI.  For example,

          [errorcode, a, b] = common_size ([1 2; 3 4], 5)
          => errorcode = 0
          => a = [ 1, 2; 3, 4 ]
          => b = [ 5, 5; 5, 5 ]

     This is useful for implementing functions where arguments can
     either be scalars or of common size.


File: octave.info,  Node: Rearranging Matrices,  Next: Applying a Function to an Array,  Prev: Finding Elements and Checking Conditions,  Up: Matrix Manipulation

16.2 Rearranging Matrices
=========================

 -- Function File:  fliplr (X)
     Return a copy of X with the order of the columns reversed.  For
     example,

          fliplr ([1, 2; 3, 4])
          =>  2  1
                   4  3

     Note that `fliplr' only work with 2-D arrays.  To flip N-d arrays
     use `flipdim' instead.

     *See also:* flipud, flipdim, rot90, rotdim.

 -- Function File:  flipud (X)
     Return a copy of X with the order of the rows reversed.  For
     example,

          flipud ([1, 2; 3, 4])
          =>  3  4
                   1  2

     Due to the difficulty of defining which axis about which to flip
     the matrix `flipud' only work with 2-d arrays.  To flip N-d arrays
     use `flipdim' instead.

     *See also:* fliplr, flipdim, rot90, rotdim.

 -- Function File:  flipdim (X, DIM)
     Return a copy of X flipped about the dimension DIM.  For example

          flipdim ([1, 2; 3, 4], 2)
          =>  2  1
                   4  3


     *See also:* fliplr, flipud, rot90, rotdim.

 -- Function File:  rot90 (X, N)
     Return a copy of X with the elements rotated counterclockwise in
     90-degree increments.  The second argument is optional, and
     specifies how many 90-degree rotations are to be applied (the
     default value is 1).  Negative values of N rotate the matrix in a
     clockwise direction.  For example,

          rot90 ([1, 2; 3, 4], -1)
          =>  3  1
                   4  2

     rotates the given matrix clockwise by 90 degrees.  The following
     are all equivalent statements:

          rot90 ([1, 2; 3, 4], -1)
          rot90 ([1, 2; 3, 4], 3)
          rot90 ([1, 2; 3, 4], 7)

     Due to the difficulty of defining an axis about which to rotate the
     matrix `rot90' only work with 2-D arrays.  To rotate N-d arrays
     use `rotdim' instead.

     *See also:* rotdim, flipud, fliplr, flipdim.

 -- Function File:  rotdim (X, N, PLANE)
     Return a copy of X with the elements rotated counterclockwise in
     90-degree increments.  The second argument is optional, and
     specifies how many 90-degree rotations are to be applied (the
     default value is 1).  The third argument is also optional and
     defines the plane of the rotation. As such PLANE is a two element
     vector containing two different valid dimensions of the matrix. If
     PLANE is not given Then the first two non-singleton dimensions are
     used.

     Negative values of N rotate the matrix in a clockwise direction.
     For example,

          rotdim ([1, 2; 3, 4], -1, [1, 2])
          =>  3  1
                   4  2

     rotates the given matrix clockwise by 90 degrees.  The following
     are all equivalent statements:

          rotdim ([1, 2; 3, 4], -1, [1, 2])
          rotdim ([1, 2; 3, 4], 3, [1, 2])
          rotdim ([1, 2; 3, 4], 7, [1, 2])


     *See also:* rot90, flipud, fliplr, flipdim.

 -- Built-in Function:  cat (DIM, ARRAY1, ARRAY2, ..., ARRAYN)
     Return the concatenation of N-d array objects, ARRAY1, ARRAY2,
     ..., ARRAYN along dimension DIM.

          A = ones (2, 2);
          B = zeros (2, 2);
          cat (2, A, B)
          => ans =

               1 1 0 0
               1 1 0 0

     Alternatively, we can concatenate A and B along the second
     dimension the following way:

          [A, B].

     DIM can be larger than the dimensions of the N-d array objects and
     the result will thus have DIM dimensions as the following example
     shows:
          cat (4, ones(2, 2), zeros (2, 2))
          => ans =

             ans(:,:,1,1) =

               1 1
               1 1

             ans(:,:,1,2) =
               0 0
               0 0


     *See also:* horzcat, vertcat.

 -- Built-in Function:  horzcat (ARRAY1, ARRAY2, ..., ARRAYN)
     Return the horizontal concatenation of N-d array objects, ARRAY1,
     ARRAY2, ..., ARRAYN along dimension 2.

     *See also:* cat, vertcat.

 -- Built-in Function:  vertcat (ARRAY1, ARRAY2, ..., ARRAYN)
     Return the vertical concatenation of N-d array objects, ARRAY1,
     ARRAY2, ..., ARRAYN along dimension 1.

     *See also:* cat, horzcat.

 -- Built-in Function:  permute (A, PERM)
     Return the generalized transpose for an N-d array object A.  The
     permutation vector PERM must contain the elements `1:ndims(a)' (in
     any order, but each element must appear just once).

     *See also:* ipermute.

 -- Built-in Function:  ipermute (A, IPERM)
     The inverse of the `permute' function.  The expression

          ipermute (permute (a, perm), perm)
     returns the original array A.

     *See also:* permute.

 -- Built-in Function:  reshape (A, M, N, ...)
 -- Built-in Function:  reshape (A, SIZ)
     Return a matrix with the given dimensions whose elements are taken
     from the matrix A.  The elements of the matrix are accessed in
     column-major order (like Fortran arrays are stored).

     For example,

          reshape ([1, 2, 3, 4], 2, 2)
               =>  1  3
                   2  4

     Note that the total number of elements in the original matrix must
     match the total number of elements in the new matrix.

     A single dimension of the return matrix can be unknown and is
     flagged by an empty argument.

 -- Built-in Function:  resize (X, M)
 -- Built-in Function:  resize (X, M, N)
     Destructively resize X.

     *Values in X are not preserved as they are with `reshape'.*

     If only M is supplied and it is a scalar, the dimension of the
     result is M-by-M.  If M is a vector, then the dimensions of the
     result are given by the elements of M.  If both M and N are
     scalars, then the dimensions of the result are M-by-N.

     *See also:* reshape, postpad.

 -- Function File: Y = circshift (X, N)
     Circularly shifts the values of the array X. N must be a vector of
     integers no longer than the number of dimensions in X. The values
     of N can be either positive or negative, which determines the
     direction in which the values or X are shifted. If an element of N
     is zero, then the corresponding dimension of X will not be
     shifted. For example

          x = [1, 2, 3; 4, 5, 6; 7, 8, 9];
          circshift (x, 1)
          =>  7, 8, 9
              1, 2, 3
              4, 5, 6
          circshift (x, -2)
          =>  7, 8, 9
              1, 2, 3
              4, 5, 6
          circshift (x, [0,1])
          =>  3, 1, 2
              6, 4, 5
              9, 7, 8


     *See also:* permute, ipermute, shiftdim.

 -- Function File: Y = shiftdim (X, N)
 -- Function File: [Y, NS] = shiftdim (X)
     Shifts the dimension of X by N, where N must be an integer scalar.
     When N is positive, the dimensions of X are shifted to the left,
     with the leading dimensions circulated to the end. If N is
     negative, then the dimensions of X are shifted to the right, with
     N leading singleton dimensions added.

     Called with a single argument, `shiftdim', removes the leading
     singleton dimensions, returning the number of dimensions removed
     in the second output argument NS.

     For example

          x = ones (1, 2, 3);
          size (shiftdim (x, -1))
          => [1, 1, 2, 3]
          size (shiftdim (x, 1))
          => [2, 3]
          [b, ns] = shiftdim (x);
          => b =  [1, 1, 1; 1, 1, 1]
          => ns = 1


     *See also:* reshape, permute, ipermute, circshift, squeeze.

 -- Function File:  shift (X, B)
 -- Function File:  shift (X, B, DIM)
     If X is a vector, perform a circular shift of length B of the
     elements of X.

     If X is a matrix, do the same for each column of X.  If the
     optional DIM argument is given, operate along this dimension

 -- Loadable Function: [S, I] = sort (X)
 -- Loadable Function: [S, I] = sort (X, DIM)
 -- Loadable Function: [S, I] = sort (X, MODE)
 -- Loadable Function: [S, I] = sort (X, DIM, MODE)
     Return a copy of X with the elements arranged in increasing order.
     For matrices, `sort' orders the elements in each column.

     For example,

          sort ([1, 2; 2, 3; 3, 1])
               =>  1  1
                   2  2
                   3  3

     The `sort' function may also be used to produce a matrix
     containing the original row indices of the elements in the sorted
     matrix.  For example,

          [s, i] = sort ([1, 2; 2, 3; 3, 1])
               => s = 1  1
                      2  2
                      3  3
               => i = 1  3
                      2  1
                      3  2

     If the optional argument DIM is given, then the matrix is sorted
     along the dimension defined by DIM. The optional argument `mode'
     defines the order in which the values will be sorted. Valid values
     of `mode' are `ascend' or `descend'.

     For equal elements, the indices are such that the equal elements
     are listed in the order that appeared in the original list.

     The `sort' function may also be used to sort strings and cell
     arrays of strings, in which case the dictionary order of the
     strings is used.

     The algorithm used in `sort' is optimized for the sorting of
     partially ordered lists.

 -- Function File:  sortrows (A, C)
     Sort the rows of the matrix A according to the order of the
     columns specified in C.  If C is omitted, a lexicographical sort
     is used. By default ascending order is used however if elements of
     C are negative then the corresponding column is sorted in
     descending order.

   Since the `sort' function does not allow sort keys to be specified,
it can't be used to order the rows of a matrix according to the values
of the elements in various columns(1) in a single call.  Using the
second output, however, it is possible to sort all rows based on the
values in a given column.  Here's an example that sorts the rows of a
matrix based on the values in the second column.

     a = [1, 2; 2, 3; 3, 1];
     [s, i] = sort (a (:, 2));
     a (i, :)
          =>  3  1
              1  2
              2  3

 -- Function File:  swap (INPUTS)
     [a1,b1] = swap(a,b)
     interchange a and b

 -- Function File:  swapcols (inputs)
      function B = swapcols(A)
      permute columns of A into reverse order

 -- Function File:  swaprows (inputs)
      function B = swaprows(A)
      permute rows of A into reverse order

 -- Function File:  tril (A, K)
 -- Function File:  triu (A, K)
     Return a new matrix formed by extracting the lower (`tril') or
     upper (`triu') triangular part of the matrix A, and setting all
     other elements to zero.  The second argument is optional, and
     specifies how many diagonals above or below the main diagonal
     should also be set to zero.

     The default value of K is zero, so that `triu' and `tril' normally
     include the main diagonal as part of the result matrix.

     If the value of K is negative, additional elements above (for
     `tril') or below (for `triu') the main diagonal are also selected.

     The absolute value of K must not be greater than the number of
     sub- or super-diagonals.

     For example,

          tril (ones (3), -1)
          =>  0  0  0
                   1  0  0
                   1  1  0

     and

          tril (ones (3), 1)
          =>  1  1  0
                   1  1  1
                   1  1  1


     *See also:* triu, diag.

 -- Function File:  vec (X)
     Return the vector obtained by stacking the columns of the matrix X
     one above the other.

 -- Function File:  vech (X)
     Return the vector obtained by eliminating all supradiagonal
     elements of the square matrix X and stacking the result one column
     above the other.

 -- Function File:  prepad (X, L, C)
 -- Function File:  postpad (X, L, C)
 -- Function File:  postpad (X, L, C, DIM)
     Prepends (appends) the scalar value C to the vector X until it is
     of length L.  If the third argument is not supplied, a value of 0
     is used.

     If `length (X) > L', elements from the beginning (end) of X are
     removed until a vector of length L is obtained.

     If X is a matrix, elements are prepended or removed from each row.

     If the optional DIM argument is given, then operate along this
     dimension.

     *See also:* postpad.

 -- Function File:  blkdiag (A, B, C, ...)
     Build a block diagonal matrix from A, B, C, ....  All the
     arguments must be numeric and are two-dimensional matrices or
     scalars.

     *See also:* diag, horzcat, vertcat.

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

   (1) For example, to first sort based on the values in column 1, and
then, for any values that are repeated in column 1, sort based on the
values found in column 2, etc.


File: octave.info,  Node: Applying a Function to an Array,  Next: Special Utility Matrices,  Prev: Rearranging Matrices,  Up: Matrix Manipulation

16.3 Applying a Function to an Array
====================================

 -- Function File: A = arrayfun (NAME, C)
 -- Function File: A = arrayfun (FUNC, C)
 -- Function File: A = arrayfun (FUNC, C, D)
 -- Function File: A = arrayfun (FUNC, C, OPTIONS)
 -- Function File: [A, B, ...] = arrayfun (FUNC, C, ...)
     Execute a function on each element of an array.  This is useful for
     functions that do not accept array arguments.  If the function does
     accept array arguments it is better to call the function directly.

     See `cellfun' for complete usage instructions.

     *See also:* cellfun.

 -- Loadable Function:  bsxfun (F, A, B)
     Applies a binary function F element-wise to two matrix arguments A
     and B. The function F must be capable of accepting two column
     vector arguments of equal length, or one column vector argument
     and a scalar.

     The dimensions of A and B must be equal or singleton. The
     singleton dimensions of the matrices will be expanded to the same
     dimensionality as the other matrix.


     *See also:* arrayfun, cellfun.


File: octave.info,  Node: Special Utility Matrices,  Next: Famous Matrices,  Prev: Applying a Function to an Array,  Up: Matrix Manipulation

16.4 Special Utility Matrices
=============================

 -- Built-in Function:  eye (X)
 -- Built-in Function:  eye (N, M)
 -- Built-in Function:  eye (..., CLASS)
     Return an identity matrix.  If invoked with a single scalar
     argument, `eye' returns a square matrix with the dimension
     specified.  If you supply two scalar arguments, `eye' takes them
     to be the number of rows and columns.  If given a vector with two
     elements, `eye' uses the values of the elements as the number of
     rows and columns, respectively.  For example,

          eye (3)
               =>  1  0  0
                   0  1  0
                   0  0  1

     The following expressions all produce the same result:

          eye (2)
          ==
          eye (2, 2)
          ==
          eye (size ([1, 2; 3, 4])

     The optional argument CLASS, allows `eye' to return an array of
     the specified type, like

          val = zeros (n,m, "uint8")

     Calling `eye' with no arguments is equivalent to calling it with
     an argument of 1.  This odd definition is for compatibility with
     MATLAB.

 -- Built-in Function:  ones (X)
 -- Built-in Function:  ones (N, M)
 -- Built-in Function:  ones (N, M, K, ...)
 -- Built-in Function:  ones (..., CLASS)
     Return a matrix or N-dimensional array whose elements are all 1.
     The arguments are handled the same as the arguments for `eye'.

     If you need to create a matrix whose values are all the same, you
     should use an expression like

          val_matrix = val * ones (n, m)

     The optional argument CLASS, allows `ones' to return an array of
     the specified type, for example

          val = ones (n,m, "uint8")

 -- Built-in Function:  zeros (X)
 -- Built-in Function:  zeros (N, M)
 -- Built-in Function:  zeros (N, M, K, ...)
 -- Built-in Function:  zeros (..., CLASS)
     Return a matrix or N-dimensional array whose elements are all 0.
     The arguments are handled the same as the arguments for `eye'.

     The optional argument CLASS, allows `zeros' to return an array of
     the specified type, for example

          val = zeros (n,m, "uint8")

 -- Function File:  repmat (A, M, N)
 -- Function File:  repmat (A, [M N])
 -- Function File:  repmat (A, [M N P ...])
     Form a block matrix of size M by N, with a copy of matrix A as
     each element.  If N is not specified, form an M by M block matrix.

 -- Loadable Function:  rand (X)
 -- Loadable Function:  rand (N, M)
 -- Loadable Function:  rand ("state", X)
 -- Loadable Function:  rand ("seed", X)
     Return a matrix with random elements uniformly distributed on the
     interval (0, 1).  The arguments are handled the same as the
     arguments for `eye'.

     You can query the state of the random number generator using the
     form

          v = rand ("state")

     This returns a column vector V of length 625. Later, you can
     restore the random number generator to the state V using the form

          rand ("state", v)

     You may also initialize the state vector from an arbitrary vector
     of length <= 625 for V.  This new state will be a hash based on the
     value of V, not V itself.

     By default, the generator is initialized from `/dev/urandom' if it
     is available, otherwise from cpu time, wall clock time and the
     current fraction of a second.

     To compute the pseudo-random sequence, `rand' uses the Mersenne
     Twister with a period of 2^19937-1 (See M. Matsumoto and T.
     Nishimura, "Mersenne Twister: A 623-dimensionally equidistributed
     uniform pseudorandom number generator", ACM Trans. on Modeling and
     Computer Simulation Vol. 8, No. 1, January pp.3-30 1998,
     `http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html').  Do
     *not* use for cryptography without securely hashing several
     returned values together, otherwise the generator state can be
     learned after reading 624 consecutive values.

     Older versions of Octave used a different random number generator.
     The new generator is used by default as it is significantly faster
     than the old generator, and produces random numbers with a
     significantly longer cycle time. However, in some circumstances it
     might be desirable to obtain the same random sequences as used by
     the old generators. To do this the keyword "seed" is used to
     specify that the old generators should be use, as in

          rand ("seed", val)

     which sets the seed of the generator to VAL. The seed of the
     generator can be queried with

          s = rand ("seed")

     However, it should be noted that querying the seed will not cause
     `rand' to use the old generators, only setting the seed will.  To
     cause `rand' to once again use the new generators, the keyword
     "state" should be used to reset the state of the `rand'.

     *See also:* randn, rande, randg, randp.

 -- Loadable Function:  randn (X)
 -- Loadable Function:  randn (N, M)
 -- Loadable Function:  randn ("state", X)
 -- Loadable Function:  randn ("seed", X)
     Return a matrix with normally distributed pseudo-random elements
     having zero mean and variance one. The arguments are handled the
     same as the arguments for `rand'.

     By default, `randn' uses a Marsaglia and Tsang Ziggurat technique
     to transform from a uniform to a normal distribution. (G.
     Marsaglia and W.W. Tsang, 'Ziggurat method for generating random
     variables', J. Statistical Software, vol 5, 2000,
     `http://www.jstatsoft.org/v05/i08/')


     *See also:* rand, rande, randg, randp.

 -- Loadable Function:  rande (X)
 -- Loadable Function:  rande (N, M)
 -- Loadable Function:  rande ("state", X)
 -- Loadable Function:  rande ("seed", X)
     Return a matrix with exponentially distributed random elements. The
     arguments are handled the same as the arguments for `rand'.

     By default, `randn' uses a Marsaglia and Tsang Ziggurat technique
     to transform from a uniform to a exponential distribution. (G.
     Marsaglia and W.W. Tsang, 'Ziggurat method for generating random
     variables', J. Statistical Software, vol 5, 2000,
     `http://www.jstatsoft.org/v05/i08/')

     *See also:* rand, randn, randg, randp.

 -- Loadable Function:  randp (L, X)
 -- Loadable Function:  randp (L, N, M)
 -- Loadable Function:  randp ("state", X)
 -- Loadable Function:  randp ("seed", X)
     Return a matrix with Poisson distributed random elements. The
     arguments are handled the same as the arguments for `rand', except
     for the argument L.

     Five different algorithms are used depending on the range of L and
     whether or not L is a scalar or a matrix.

    For scalar L <= 12, use direct method.
          Press, et al., 'Numerical Recipes in C', Cambridge University
          Press, 1992.

    For scalar L > 12, use rejection method.[1]
          Press, et al., 'Numerical Recipes in C', Cambridge University
          Press, 1992.

    For matrix L <= 10, use inversion method.[2]
          Stadlober E., et al., WinRand source code, available via FTP.

    For matrix L > 10, use patchwork rejection method.
          Stadlober E., et al., WinRand source code, available via FTP,
          or H. Zechner, 'Efficient sampling from continuous and
          discrete unimodal distributions', Doctoral Dissertation,
          156pp., Technical University Graz, Austria, 1994.

    For L > 1e8, use normal approximation.
          L. Montanet, et al., 'Review of Particle Properties',
          Physical Review D 50 p1284, 1994


     *See also:* rand, randn, rande, randg.

 -- Loadable Function:  randg (A, X)
 -- Loadable Function:  randg (A, N, M)
 -- Loadable Function:  randg ("state", X)
 -- Loadable Function:  randg ("seed", X)
     Return a matrix with `gamma(A,1)' distributed random elements.
     The arguments are handled the same as the arguments for `rand',
     except for the argument A.

     This can be used to generate many distributions:

    `gamma (a, b)' for `a > -1', `b > 0'
               r = b * randg (a)

    `beta (a, b)' for `a > -1', `b > -1'
               r1 = randg (a, 1)
               r = r1 / (r1 + randg (b, 1))

    `Erlang (a, n)'
               r = a * randg (n)

    `chisq (df)' for `df > 0'
               r = 2 * randg (df / 2)

    `t(df)' for `0 < df < inf' (use randn if df is infinite)
               r = randn () / sqrt (2 * randg (df / 2) / df)

    `F (n1, n2)' for `0 < n1', `0 < n2'
               ## r1 equals 1 if n1 is infinite
               r1 = 2 * randg (n1 / 2) / n1
               ## r2 equals 1 if n2 is infinite
               r2 = 2 * randg (n2 / 2) / n2
               r = r1 / r2

    negative `binomial (n, p)' for `n > 0', `0 < p <= 1'
               r = randp ((1 - p) / p * randg (n))

    non-central `chisq (df, L)', for `df >= 0' and `L > 0'
          (use chisq if `L = 0')
               r = randp (L / 2)
               r(r > 0) = 2 * randg (r(r > 0))
               r(df > 0) += 2 * randg (df(df > 0)/2)

    `Dirichlet (a1, ..., ak)'
               r = (randg (a1), ..., randg (ak))
               r = r / sum (r)


     *See also:* rand, randn, rande, randp.

   The new random generators all use a common Mersenne Twister
generator, and so the state of only one of the generators needs to be
reset.  The old generator function use separate generators. This
ensures that

     rand ("seed", 13);
     randn ("seed", 13);
     u = rand (100, 1);
     n = randn (100, 1);

and

     rand ("seed", 13);
     randn ("seed", 13);
     u = zeros (100, 1);
     n = zeros (100, 1);
     for i = 1:100
       u(i) = rand ();
       n(i) = randn ();
     end

produce equivalent results.

   Normally, `rand' and `randn' obtain their initial seeds from the
system clock, so that the sequence of random numbers is not the same
each time you run Octave.  If you really do need for to reproduce a
sequence of numbers exactly, you can set the seed to a specific value.

   If it is invoked without arguments, `rand' and `randn' return a
single element of a random sequence.

   The `rand' and `randn' functions use Fortran code from RANLIB, a
library of fortran routines for random number generation, compiled by
Barry W. Brown and James Lovato of the Department of Biomathematics at
The University of Texas, M.D. Anderson Cancer Center, Houston, TX 77030.

 -- Function File:  randperm (N)
     Return a row vector containing a random permutation of the
     integers from 1 to N.

 -- Built-in Function:  diag (V, K)
     Return a diagonal matrix with vector V on diagonal K.  The second
     argument is optional.  If it is positive, the vector is placed on
     the K-th super-diagonal.  If it is negative, it is placed on the
     -K-th sub-diagonal.  The default value of K is 0, and the vector
     is placed on the main diagonal.  For example,

          diag ([1, 2, 3], 1)
               =>  0  1  0  0
                   0  0  2  0
                   0  0  0  3
                   0  0  0  0

     Given a matrix argument, instead of a vector, `diag' extracts the
     K-th diagonal of the matrix.

   The functions `linspace' and `logspace' make it very easy to create
vectors with evenly or logarithmically spaced elements.  *Note Ranges::.

 -- Built-in Function:  linspace (BASE, LIMIT, N)
     Return a row vector with N linearly spaced elements between BASE
     and LIMIT.  If the number of elements is greater than one, then
     the BASE and LIMIT are always included in the range.  If BASE is
     greater than LIMIT, the elements are stored in decreasing order.
     If the number of points is not specified, a value of 100 is used.

     The `linspace' function always returns a row vector.

     For compatibility with MATLAB, return the second argument if fewer
     than two values are requested.

 -- Function File:  logspace (BASE, LIMIT, N)
     Similar to `linspace' except that the values are logarithmically
     spaced from 10^base to 10^limit.

     If LIMIT is equal to pi, the points are between 10^base and pi,
     _not_ 10^base and 10^pi, in order to  be compatible with the
     corresponding MATLAB function.

     Also for compatibility, return the second argument if fewer than
     two values are requested.

     *See also:* linspace.


File: octave.info,  Node: Famous Matrices,  Prev: Special Utility Matrices,  Up: Matrix Manipulation

16.5 Famous Matrices
====================

The following functions return famous matrix forms.

 -- Function File:  hadamard (N)
     Construct a Hadamard matrix HN of size N-by-N. The size N must be
     of the form `2 ^ K * P' in which P is one of 1, 12, 20 or 28. The
     returned matrix is normalized, meaning `Hn(:,1) == 1' and `H(1,:)
     == 1'.

     Some of the properties of Hadamard matrices are:

        * `kron (HM, HN)' is a Hadamard matrix of size M-by-N.

        * `Hn * Hn' == N * eye (N)'.

        * The rows of HN are orthogonal.

        * `det (A) <= det (HN)' for all A with `abs (A (I, J)) <= 1'.

        * Multiply any row or column by -1 and still have a Hadamard
          matrix.


 -- Function File:  hankel (C, R)
     Return the Hankel matrix constructed given the first column C, and
     (optionally) the last row R.  If the last element of C is not the
     same as the first element of R, the last element of C is used.  If
     the second argument is omitted, it is assumed to be a vector of
     zeros with the same size as C.

     A Hankel matrix formed from an m-vector C, and an n-vector R, has
     the elements

          H(i,j) = c(i+j-1),  i+j-1 <= m;
          H(i,j) = r(i+j-m),  otherwise


     *See also:* vander, sylvester_matrix, hilb, invhilb, toeplitz.

 -- Function File:  hilb (N)
     Return the Hilbert matrix of order N.  The i, j element of a
     Hilbert matrix is defined as

          H (i, j) = 1 / (i + j - 1)


     *See also:* hankel, vander, sylvester_matrix, invhilb, toeplitz.

 -- Function File:  invhilb (N)
     Return the inverse of a Hilbert matrix of order N.  This can be
     computed exactly using

                      (i+j)         /n+i-1\  /n+j-1\   /i+j-2\ 2
           A(i,j) = -1      (i+j-1)(       )(       ) (       )
                                    \ n-j /  \ n-i /   \ i-2 /

                  = p(i) p(j) / (i+j-1)
     where
                       k  /k+n-1\   /n\
              p(k) = -1  (       ) (   )
                          \ k-1 /   \k/

     The validity of this formula can easily be checked by expanding
     the binomial coefficients in both formulas as factorials.  It can
     be derived more directly via the theory of Cauchy matrices: see J.
     W. Demmel, Applied Numerical Linear Algebra, page 92.

     Compare this with the numerical calculation of `inverse (hilb
     (n))', which suffers from the ill-conditioning of the Hilbert
     matrix, and the finite precision of your computer's floating point
     arithmetic.

     *See also:* hankel, vander, sylvester_matrix, hilb, toeplitz.

 -- Function File:  magic (N)
     Create an N-by-N magic square. Note that `magic (2)' is undefined
     since there is no 2-by-2 magic square.


 -- Function File:  pascal (N, T)
     Return the Pascal matrix of order N if `T = 0'.  T defaults to 0.
     Return lower triangular Cholesky factor of the Pascal matrix if `T
     = 1'. This matrix is its own inverse, that is `pascal (N, 1) ^ 2
     == eye (N)'.  If `T = 2', return a transposed and  permuted
     version of `pascal (N, 1)', which is the cube-root of the identity
     matrix. That is `pascal (N, 2) ^ 3 == eye (N)'.


     *See also:* hankel, vander, sylvester_matrix, hilb, invhilb,
     toeplitz           hadamard, wilkinson, compan, rosser.

 -- Function File:  rosser ()
     Returns the Rosser matrix. This is a difficult test case used to
     test eigenvalue algorithms.


     *See also:* hankel, vander, sylvester_matrix, hilb, invhilb,
     toeplitz           hadamard, wilkinson, compan, pascal.

 -- Function File:  sylvester_matrix (K)
     Return the Sylvester matrix of order n = 2^k.

     *See also:* hankel, vander, hilb, invhilb, toeplitz.

 -- Function File:  toeplitz (C, R)
     Return the Toeplitz matrix constructed given the first column C,
     and (optionally) the first row R.  If the first element of C is
     not the same as the first element of R, the first element of C is
     used.  If the second argument is omitted, the first row is taken
     to be the same as the first column.

     A square Toeplitz matrix has the form:

          c(0)  r(1)   r(2)  ...  r(n)
          c(1)  c(0)   r(1)  ... r(n-1)
          c(2)  c(1)   c(0)  ... r(n-2)
           .     ,      ,   .      .
           .     ,      ,     .    .
           .     ,      ,       .  .
          c(n) c(n-1) c(n-2) ...  c(0)


     *See also:* hankel, vander, sylvester_matrix, hilb, invhilb.

 -- Function File:  vander (C)
     Return the Vandermonde matrix whose next to last column is C.

     A Vandermonde matrix has the form:

          c(1)^(n-1) ... c(1)^2  c(1)  1
          c(2)^(n-1) ... c(2)^2  c(2)  1
              .     .      .      .    .
              .       .    .      .    .
              .         .  .      .    .
          c(n)^(n-1) ... c(n)^2  c(n)  1


     *See also:* hankel, sylvester_matrix, hilb, invhilb, toeplitz.

 -- Function File:  wilkinson (N)
     Return the Wilkinson matrix of order N.


     *See also:* hankel, vander, sylvester_matrix, hilb, invhilb,
     toeplitz           hadamard, rosser, compan, pascal.


File: octave.info,  Node: Arithmetic,  Next: Linear Algebra,  Prev: Matrix Manipulation,  Up: Top

17 Arithmetic
*************

Unless otherwise noted, all of the functions described in this chapter
will work for real and complex scalar or matrix arguments.

* Menu:

* Utility Functions::
* Complex Arithmetic::
* Trigonometry::
* Sums and Products::
* Special Functions::
* Coordinate Transformations::
* Mathematical Constants::


File: octave.info,  Node: Utility Functions,  Next: Complex Arithmetic,  Up: Arithmetic

17.1 Utility Functions
======================

The following functions are available for working with complex numbers.
Each expects a single argument.  They are called "mapping functions"
because when given a matrix argument, they apply the given function to
each element of the matrix.

 -- Mapping Function:  ceil (X)
     Return the smallest integer not less than X.  If X is complex,
     return `ceil (real (X)) + ceil (imag (X)) * I'.

 -- Function File:  cplxpair (Z, TOL, DIM)
     Sort the numbers Z into complex conjugate pairs ordered by
     increasing real part.  With identical real parts, order by
     increasing imaginary magnitude. Place the negative imaginary
     complex number first within each pair. Place all the real numbers
     after all the complex pairs (those with `abs (imag (Z) / Z) <
     TOL)', where the default value of TOL is `100 * EPS'.

     By default the complex pairs are sorted along the first
     non-singleton dimension of Z. If DIM is specified, then the complex
     pairs are sorted along this dimension.

     Signal an error if some complex numbers could not be paired.
     Requires all complex numbers to be exact conjugates within tol, or
     signals an error. Note that there are no guarantees on the order
     of the returned pairs with identical real parts but differing
     imaginary parts.

          cplxpair (exp(2i*pi*[0:4]'/5)) == exp(2i*pi*[3; 2; 4; 1; 0]/5)

 -- Function File: D = del2 (M)
 -- Function File: D = del2 (M, H)
 -- Function File: D = del2 (M, DX, DY, ...)
     Calculates the discrete Laplace operator. If M is a matrix this is
     defined as

                1    / d^2            d^2         \
          D  = --- * | ---  M(x,y) +  ---  M(x,y) |
                4    \ dx^2           dy^2        /

     The above to continued to N-dimensional arrays calculating the
     second derivative over the higher dimensions.

     The spacing between evaluation points may be defined by H, which
     is a scalar defining the spacing in all dimensions. Or
     alternative, the spacing in each dimension may be defined
     separately by DX, DY, etc.  Scalar spacing values give equidistant
     spacing, whereas vector spacing values can be used to specify
     variable spacing. The length of the vectors must match the
     respective dimension of M. The default spacing value is 1.

     You need at least 3 data points for each dimension. Boundary
     points are calculated as the linear extrapolation of the interior
     points.


     *See also:* gradient, diff.

 -- Mapping Function:  exp (X)
     Compute the exponential of X.  To compute the matrix exponential,
     see *Note Linear Algebra::.

 -- Function File: P = factor (Q)
 -- Function File: [P, N] = factor (Q)
     Return prime factorization of Q. That is `prod (P) == Q'. If `Q ==
     1', returns 1.

     With two output arguments, returns the unique primes P and their
     multiplicities. That is `prod (P .^ N) == Q'.


 -- Function File:  factorial (N)
     Return the factorial of N. If N is scalar, this is equivalent to
     `prod (1:N)'.  If N is an array, the factorial of the elements of
     the array are returned.

 -- Mapping Function:  fix (X)
     Truncate X toward zero.  If X is complex, return `fix (real (X)) +
     fix (imag (X)) * I'.

 -- Mapping Function:  floor (X)
     Return the largest integer not greater than X.  If X is complex,
     return `floor (real (X)) + floor (imag (X)) * I'.

 -- Mapping Function:  fmod (X, Y)
     Compute the floating point remainder of dividing X by Y using the
     C library function `fmod'.  The result has the same sign as X.  If
     Y is zero, the result implementation-defined.

 -- Loadable Function: G = gcd (A1, ...)
 -- Loadable Function: [G, V1, ...] = gcd (A1, ...)
     If a single argument is given then compute the greatest common
     divisor of the elements of this argument. Otherwise if more than
     one argument is given all arguments must be the same size or
     scalar. In this case the greatest common divisor is calculated for
     element individually. All elements must be integers. For example,

          gcd ([15, 20])
              =>  5

     and

          gcd ([15, 9], [20 18])
              =>  5  9

     Optional return arguments V1, etc, contain integer vectors such
     that,

          G = V1 .* A1 + V2 .* A2 + ...

     For backward compatibility with previous versions of this
     function, when all arguments are scalar, a single return argument
     V1 containing all of the values of V1, ... is acceptable.

     *See also:* lcm, min, max, ceil, floor.

 -- Function File: X =  gradient (M)
 -- Function File: [X, Y, ...] =  gradient (M)
 -- Function File: [...] =  gradient (M, S)
 -- Function File: [...] =  gradient (M, DX, DY, ...)
     Calculates the gradient. `X = gradient (M)' calculates the one
     dimensional gradient if M is a vector. If M is a matrix the
     gradient is calculated for each row.

     `[X, Y] = gradient (M)' calculates the one dimensional gradient
     for each direction if M if M is a matrix. Additional return
     arguments can be use for multi-dimensional matrices.

     Spacing values between two points can be provided by the DX, DY or
     H parameters. If H is supplied it is assumed to be the spacing in
     all directions. Otherwise, separate values of the spacing can be
     supplied by the DX, etc variables.  A scalar value specifies an
     equidistant spacing, while a vector value can be used to specify a
     variable spacing. The length must match their respective dimension
     of M.

     At boundary points a linear extrapolation is applied. Interior
     points are calculated with the first approximation of the
     numerical gradient

          y'(i) = 1/(x(i+1)-x(i-1)) *(y(i-1)-y(i+1)).


 -- Mapping Function:  lcm (X, ...)
     Compute the least common multiple of the elements of X, or the
     list of all the arguments.  For example,

          lcm (a1, ..., ak)

     is the same as

          lcm ([a1, ..., ak]).

     All elements must be the same size or scalar.

     *See also:* gcd, min, max, ceil, floor.

 -- Mapping Function:  log (X)
     Compute the natural logarithm for each element of X.  To compute
     the matrix logarithm, see *Note Linear Algebra::.

     *See also:* log2, log10, logspace, exp.

 -- Mapping Function:  log10 (X)
     Compute the base-10 logarithm for each element of X.

     *See also:* log, log2, logspace, exp.

 -- Mapping Function:  log2 (X)
 -- Mapping Function: [F, E] = log2 (X)
     Compute the base-2 logarithm of X.  With two outputs, returns F
     and E such that  1/2 <= abs(f) < 1 and x = f * 2^e.

     *See also:* log, log10, logspace, exp.

 -- Mapping Function:  max (X, Y, DIM)
 -- Mapping Function: [W, IW] = max (X)
     For a vector argument, return the maximum value.  For a matrix
     argument, return the maximum value from each column, as a row
     vector, or over the dimension DIM if defined. For two matrices (or
     a matrix and scalar), return the pair-wise maximum.  Thus,

          max (max (X))

     returns the largest element of X, and

          max (2:5, pi)
              =>  3.1416  3.1416  4.0000  5.0000
     compares each element of the range `2:5' with `pi', and
     returns a row vector of the maximum values.

     For complex arguments, the magnitude of the elements are used for
     comparison.

     If called with one input and two output arguments, `max' also
     returns the first index of the maximum value(s). Thus,

          [x, ix] = max ([1, 3, 5, 2, 5])
              =>  x = 5
                  ix = 3

 -- Mapping Function:  min (X, Y, DIM)
 -- Mapping Function: [W, IW] = min (X)
     For a vector argument, return the minimum value.  For a matrix
     argument, return the minimum value from each column, as a row
     vector, or over the dimension DIM if defined. For two matrices (or
     a matrix and scalar), return the pair-wise minimum.  Thus,

          min (min (X))

     returns the smallest element of X, and

          min (2:5, pi)
              =>  2.0000  3.0000  3.1416  3.1416
     compares each element of the range `2:5' with `pi', and
     returns a row vector of the minimum values.

     For complex arguments, the magnitude of the elements are used for
     comparison.

     If called with one input and two output arguments, `min' also
     returns the first index of the minimum value(s). Thus,

          [x, ix] = min ([1, 3, 0, 2, 5])
              =>  x = 0
                  ix = 3

 -- Mapping Function:  mod (X, Y)
     Compute modulo function. Conceptually this is given by

          x - y .* floor (x ./ y)

     and is written in a manner that the correct modulus is returned for
     integer types. This function handles negative values correctly.
     That is `mod (-1, 3)' is 2, not -1 as `rem (-1, 3)' returns.
     Also, `mod (X, 0)' returns X.

     An error message is printed if the dimensions of the arguments do
     not agree, or if either of the arguments is complex.

     *See also:* rem, round.

 -- Function File:  nextpow2 (X)
     If X is a scalar, returns the first integer N such that  2^n >=
     abs (x).

     If X is a vector, return `nextpow2 (length (X))'.

     *See also:* pow2.

 -- Function File:  nthroot (X, N)
     Compute the nth root of X, returning real results for real
     components of X. For example

          nthroot (-1, 3)
          => -1
          (-1) ^ (1 / 3)
          => 0.50000 - 0.86603i


 -- Mapping Function:  pow2 (X)
 -- Mapping Function:  pow2 (F, E)
     With one argument, computes  2 .^ x for each element of X.  With
     two arguments, returns  f .* (2 .^ e).

     *See also:* nextpow2.

 -- Function File:  primes (N)
     Return all primes up to N.

     Note that if you need a specific number of primes, you can use the
     fact the distance from one prime to the next is on average
     proportional to the logarithm of the prime.  Integrating, you find
     that there are about k primes less than k \log ( 5 k ).

     The algorithm used is called the Sieve of Erastothenes.

 -- Mapping Function:  rem (X, Y)
     Return the remainder of `X / Y', computed using the expression

          x - y .* fix (x ./ y)

     An error message is printed if the dimensions of the arguments do
     not agree, or if either of the arguments is complex.

     *See also:* mod, round.

 -- Mapping Function:  round (X)
     Return the integer nearest to X.  If X is complex, return `round
     (real (X)) + round (imag (X)) * I'.

     *See also:* rem.

 -- Mapping Function:  sign (X)
     Compute the "signum" function, which is defined as

                     -1, x < 0;
          sign (x) =  0, x = 0;
                      1, x > 0.

     For complex arguments, `sign' returns `x ./ abs (X)'.

 -- Mapping Function:  sqrt (X)
     Compute the square root of X.  If X is negative, a complex result
     is returned.  To compute the matrix square root, see *Note Linear
     Algebra::.


File: octave.info,  Node: Complex Arithmetic,  Next: Trigonometry,  Prev: Utility Functions,  Up: Arithmetic

17.2 Complex Arithmetic
=======================

The following functions are available for working with complex numbers.
Each expects a single argument.  Given a matrix they work on an
element by element basis.  In the descriptions of the following
functions, Z is the complex number X + IY, where I is defined as `sqrt
(-1)'.

 -- Mapping Function:  abs (Z)
     Compute the magnitude of Z, defined as |Z| = `sqrt (x^2 + y^2)'.

     For example,

          abs (3 + 4i)
               => 5

 -- Mapping Function:  arg (Z)
 -- Mapping Function:  angle (Z)
     Compute the argument of Z, defined as THETA = `atan (Y/X)'.  in
     radians.

     For example,

          arg (3 + 4i)
               => 0.92730

 -- Mapping Function:  conj (Z)
     Return the complex conjugate of Z, defined as `conj (Z)' = X - IY.

     *See also:* real, imag.

 -- Mapping Function:  imag (Z)
     Return the imaginary part of Z as a real number.

     *See also:* real, conj.

 -- Mapping Function:  real (Z)
     Return the real part of Z.

     *See also:* imag, conj.


File: octave.info,  Node: Trigonometry,  Next: Sums and Products,  Prev: Complex Arithmetic,  Up: Arithmetic

17.3 Trigonometry
=================

Octave provides the following trigonometric functions.  Angles are
specified in radians.  To convert from degrees to radians multiply by
`pi/180'  (e.g. `sin (30 * pi/180)' returns the sine of 30 degrees).

 -- Mapping Function:  sin (X)
     Compute the sine of each element of X.

 -- Mapping Function:  cos (X)
     Compute the cosine of each element of X.

 -- Mapping Function:  tan (Z)
     Compute tangent of each element of X.

 -- Mapping Function:  sec (X)
     Compute the secant of each element of X.

 -- Mapping Function:  csc (X)
     Compute the cosecant of each element of X.

 -- Mapping Function:  cot (X)
     Compute the cotangent of each element of X.

 -- Mapping Function:  asin (X)
     Compute the inverse sine of each element of X.

 -- Mapping Function:  acos (X)
     Compute the inverse cosine of each element of X.

 -- Mapping Function:  atan (X)
     Compute the inverse tangent of each element of X.

 -- Mapping Function:  asec (X)
     Compute the inverse secant of each element of X.

 -- Mapping Function:  acsc (X)
     Compute the inverse cosecant of each element of X.

 -- Mapping Function:  acot (X)
     Compute the inverse cotangent of each element of X.

 -- Mapping Function:  sinh (X)
     Compute the hyperbolic sine of each element of X.

 -- Mapping Function:  cosh (X)
     Compute the hyperbolic cosine of each element of X.

 -- Mapping Function:  tanh (X)
     Compute hyperbolic tangent of each element of X.

 -- Mapping Function:  sech (X)
     Compute the hyperbolic secant of each element of X.

 -- Mapping Function:  csch (X)
     Compute the hyperbolic cosecant of each element of X.

 -- Mapping Function:  coth (X)
     Compute the hyperbolic cotangent of each element of X.

 -- Mapping Function:  asinh (X)
     Compute the inverse hyperbolic sine of each element of X.

 -- Mapping Function:  acosh (X)
     Compute the inverse hyperbolic cosine of each element of X.

 -- Mapping Function:  atanh (X)
     Compute the inverse hyperbolic tangent of each element of X.

 -- Mapping Function:  asech (X)
     Compute the inverse hyperbolic secant of each element of X.

 -- Mapping Function:  acsch (X)
     Compute the inverse hyperbolic cosecant of each element of X.

 -- Mapping Function:  acoth (X)
     Compute the inverse hyperbolic cotangent of each element of X.

   Each of these functions expects a single argument.  For matrix
arguments, they work on an element by element basis.  For example,

     sin ([1, 2; 3, 4])
          =>  0.84147   0.90930
              0.14112  -0.75680

 -- Mapping Function:  atan2 (Y, X)
     Compute atan (Y / X) for corresponding elements of Y and X.  The
     result is in range -pi to pi.

   In addition to the trigonometric functions that work with radians,
Octave also provides the following functions which work with degrees.

 -- Function File:  sind (X)
     Compute the sine of each element of X.  Returns zero in elements
     for which `X/180' is an integer.

     *See also:* sin, cosd, tand, acosd, asind, atand.

 -- Function File:  cosd (X)
     Compute the cosine of an angle in degrees.  Returns zero in
     elements for which `(X-90)/180' is an integer.

     *See also:* cos, sind, tand, acosd, asind, atand.

 -- Function File:  tand (X)
     Compute the tangent of an angle in degrees.  Returns zero for
     elements of for which `X/180' is an integer and `Inf' for elements
     where `(X-90)/180' is an integer.

     *See also:* tan, cosd, sind, acosd, asind, atand.

 -- Function File:  secd (X)
     Compute the secant of an angle in degrees.

     *See also:* sec, cscd, sind, cosd.

 -- Function File:  cscd (X)
     Compute the cosecant of an angle in degrees.

     *See also:* csc, secd, sind, cosd.

 -- Function File:  cotd (X)
     Compute the cotangent of an angle in degrees.

     *See also:* cot, tand.

 -- Function File:  asind (X)
     Compute the inverse sine of an angle in degrees.

     *See also:* asin, sind, acosd.

 -- Function File:  acosd (X)
     Compute the inverse cosine of an angle in degrees.

     *See also:* acos, cosd, asecd.

 -- Function File:  atand (X)
     Compute the inverse tangent of an angle in degrees.

     *See also:* acot, tand.

 -- Function File:  asecd (X)
     Compute inverse secant in degrees.

     *See also:* asec, secd, acscd.

 -- Function File:  acscd (X)
     Compute the inverse cosecant of an angle in degrees.

     *See also:* acsc, cscd, asecd.

 -- Function File:  acotd (X)
     Compute the inverse cotangent of an angle in degrees.

     *See also:* atan, tand.


File: octave.info,  Node: Sums and Products,  Next: Special Functions,  Prev: Trigonometry,  Up: Arithmetic

17.4 Sums and Products
======================

 -- Built-in Function:  sum (X, DIM)
 -- Built-in Function:  sum (..., 'native')
     Sum of elements along dimension DIM.  If DIM is omitted, it
     defaults to 1 (column-wise sum).

     As a special case, if X is a vector and DIM is omitted, return the
     sum of the elements.

     If the optional argument 'native' is given, then the sum is
     performed in the same type as the original argument, rather than
     in the default double type. For example

          sum ([true, true])
            => 2
          sum ([true, true], 'native')
            => true

 -- Built-in Function:  prod (X, DIM)
     Product of elements along dimension DIM.  If DIM is omitted, it
     defaults to 1 (column-wise products).

     As a special case, if X is a vector and DIM is omitted, return the
     product of the elements.

 -- Built-in Function:  cumsum (X, DIM)
     Cumulative sum of elements along dimension DIM.  If DIM is
     omitted, it defaults to 1 (column-wise cumulative sums).

     As a special case, if X is a vector and DIM is omitted, return the
     cumulative sum of the elements as a vector with the same
     orientation as X.

 -- Built-in Function:  cumprod (X, DIM)
     Cumulative product of elements along dimension DIM.  If DIM is
     omitted, it defaults to 1 (column-wise cumulative products).

     As a special case, if X is a vector and DIM is omitted, return the
     cumulative product of the elements as a vector with the same
     orientation as X.

 -- Built-in Function:  sumsq (X, DIM)
     Sum of squares of elements along dimension DIM.  If DIM is
     omitted, it defaults to 1 (column-wise sum of squares).

     As a special case, if X is a vector and DIM is omitted, return the
     sum of squares of the elements.

     This function is conceptually equivalent to computing
          sum (x .* conj (x), dim)
     but it uses less memory and avoids calling conj if X is real.

 -- Function File:  accumarray (SUBS, VALS, SZ, FUN, FILLVAL, ISSPARSE)
 -- Function File:  accumarray (CSUBS, VALS, ...)
     Create an array by accumulating the elements of a vector into the
     positions defined by their subscripts. The subscripts are defined
     by the rows of the matrix SUBS and the values by VALS. Each row of
     SUBS corresponds to one of the values in VALS.

     The size of the matrix will be determined by the subscripts
     themselves.  However, if SZ is defined it determines the matrix
     size. The length of SZ must correspond to the number of columns in
     SUBS.

     The default action of `accumarray' is to sum the elements with the
     same subscripts. This behavior can be modified by defining the FUN
     function. This should be a function or function handle that
     accepts a column vector and returns a scalar. The result of the
     function should not depend on the order of the subscripts.

     The elements of the returned array that have no subscripts
     associated with them are set to zero. Defining FILLVAL to some
     other value allows these values to be defined.

     By default `accumarray' returns a full matrix. If ISSPARSE is
     logically true, then a sparse matrix is returned instead.

     An example of the use of `accumarray' is:

          accumarray ([1,1,1;2,1,2;2,3,2;2,1,2;2,3,2], 101:105)
          => ans(:,:,1) = [101, 0, 0; 0, 0, 0]
             ans(:,:,2) = [0, 0, 0; 206, 0, 208]


File: octave.info,  Node: Special Functions,  Next: Coordinate Transformations,  Prev: Sums and Products,  Up: Arithmetic

17.5 Special Functions
======================

 -- Loadable Function: [J, IERR] = besselj (ALPHA, X, OPT)
 -- Loadable Function: [Y, IERR] = bessely (ALPHA, X, OPT)
 -- Loadable Function: [I, IERR] = besseli (ALPHA, X, OPT)
 -- Loadable Function: [K, IERR] = besselk (ALPHA, X, OPT)
 -- Loadable Function: [H, IERR] = besselh (ALPHA, K, X, OPT)
     Compute Bessel or Hankel functions of various kinds:

    `besselj'
          Bessel functions of the first kind. If the argument OPT is
          supplied, the result is multiplied by `exp(-abs(imag(x)))'.

    `bessely'
          Bessel functions of the second kind. If the argument OPT is
          supplied, the result is multiplied by `exp(-abs(imag(x)))'.

    `besseli'
          Modified Bessel functions of the first kind.  If the argument
          OPT is supplied, the result is multiplied by
          `exp(-abs(real(x)))'.

    `besselk'
          Modified Bessel functions of the second kind.  If the
          argument OPT is supplied, the result is multiplied by
          `exp(x)'.

    `besselh'
          Compute Hankel functions of the first (K = 1) or second (K =
          2) kind. If the argument OPT is supplied, the result is
          multiplied by `exp (-I*X)' for K = 1 or `exp (I*X)' for K = 2.

     If ALPHA is a scalar, the result is the same size as X.  If X is a
     scalar, the result is the same size as ALPHA.  If ALPHA is a row
     vector and X is a column vector, the result is a matrix with
     `length (X)' rows and `length (ALPHA)' columns.  Otherwise, ALPHA
     and X must conform and the result will be the same size.

     The value of ALPHA must be real.  The value of X may be complex.

     If requested, IERR contains the following status information and
     is the same size as the result.

       0. Normal return.

       1. Input error, return `NaN'.

       2. Overflow, return `Inf'.

       3. Loss of significance by argument reduction results in less
          than half of machine accuracy.

       4. Complete loss of significance by argument reduction, return
          `NaN'.

       5. Error--no computation, algorithm termination condition not
          met, return `NaN'.

 -- Loadable Function: [A, IERR] = airy (K, Z, OPT)
     Compute Airy functions of the first and second kind, and their
     derivatives.

           K   Function   Scale factor (if 'opt' is supplied)
          ---  --------   ---------------------------------------
           0   Ai (Z)     exp ((2/3) * Z * sqrt (Z))
           1   dAi(Z)/dZ  exp ((2/3) * Z * sqrt (Z))
           2   Bi (Z)     exp (-abs (real ((2/3) * Z *sqrt (Z))))
           3   dBi(Z)/dZ  exp (-abs (real ((2/3) * Z *sqrt (Z))))

     The function call `airy (Z)' is equivalent to `airy (0, Z)'.

     The result is the same size as Z.

     If requested, IERR contains the following status information and
     is the same size as the result.

       0. Normal return.

       1. Input error, return `NaN'.

       2. Overflow, return `Inf'.

       3. Loss of significance by argument reduction results in less
          than half  of machine accuracy.

       4. Complete loss of significance by argument reduction, return
          `NaN'.

       5. Error--no computation, algorithm termination condition not
          met, return `NaN'.

 -- Mapping Function:  beta (A, B)
     Return the Beta function,

          beta (a, b) = gamma (a) * gamma (b) / gamma (a + b).

 -- Mapping Function:  betainc (X, A, B)
     Return the incomplete Beta function,

                                                x
                                               /
          betainc (x, a, b) = beta (a, b)^(-1) | t^(a-1) (1-t)^(b-1) dt.
                                               /
                                            t=0

     If x has more than one component, both A and B must be scalars.
     If X is a scalar, A and B must be of compatible dimensions.

 -- Mapping Function:  betaln (A, B)
     Return the log of the Beta function,

          betaln (a, b) = gammaln (a) + gammaln (b) - gammaln (a + b)


     *See also:* beta, betai, gammaln.

 -- Mapping Function:  bincoeff (N, K)
     Return the binomial coefficient of N and K, defined as

           /   \
           | n |    n (n-1) (n-2) ... (n-k+1)
           |   |  = -------------------------
           | k |               k!
           \   /

     For example,

          bincoeff (5, 2)
          => 10

 -- Mapping Function:  erf (Z)
     Computes the error function,

                                   z
                                  /
          erf (z) = (2/sqrt (pi)) | e^(-t^2) dt
                                  /
                               t=0


     *See also:* erfc, erfinv.

 -- Mapping Function:  erfc (Z)
     Computes the complementary error function, `1 - erf (Z)'.

     *See also:* erf, erfinv.

 -- Mapping Function:  erfinv (Z)
     Computes the inverse of the error function.

     *See also:* erf, erfc.

 -- Mapping Function:  gamma (Z)
     Computes the Gamma function,

                      infinity
                      /
          gamma (z) = | t^(z-1) exp (-t) dt.
                      /
                   t=0


     *See also:* gammai, lgamma.

 -- Mapping Function:  gammainc (X, A)
     Compute the normalized incomplete gamma function,

                                          x
                                1        /
          gammainc (x, a) = ---------    | exp (-t) t^(a-1) dt
                            gamma (a)    /
                                      t=0

     with the limiting value of 1 as X approaches infinity.  The
     standard notation is P(a,x), e.g. Abramowitz and Stegun (6.5.1).

     If A is scalar, then `gammainc (X, A)' is returned for each
     element of X and vice versa.

     If neither X nor A is scalar, the sizes of X and A must agree, and
     GAMMAINC is applied element-by-element.

     *See also:* gamma, lgamma.

 -- Function File: L = legendre (N, X)
     Legendre Function of degree n and order m where all values for m =
     0..N are returned.  N must be a scalar in the range [0..255].  The
     return value has one dimension more than X.

          The Legendre Function of degree n and order m

           m        m       2  m/2   d^m
          P(x) = (-1) * (1-x  )    * ----  P (x)
           n                         dx^m   n

          with:
          Legendre polynomial of degree n

                    1     d^n   2    n
          P (x) = ------ [----(x - 1)  ]
           n      2^n n!  dx^n

          legendre(3,[-1.0 -0.9 -0.8]) returns the matrix

           x  |   -1.0   |   -0.9   |  -0.8
          ------------------------------------
          m=0 | -1.00000 | -0.47250 | -0.08000
          m=1 |  0.00000 | -1.99420 | -1.98000
          m=2 |  0.00000 | -2.56500 | -4.32000
          m=3 |  0.00000 | -1.24229 | -3.24000

 -- Mapping Function:  lgamma (X)
 -- Mapping Function:  gammaln (X)
     Return the natural logarithm of the absolute value of the gamma
     function of X.

     *See also:* gamma, gammai.

 -- Function File:  cross (X, Y, DIM)
     Computes the vector cross product of the two 3-dimensional vectors
     X and Y.

          cross ([1,1,0], [0,1,1])
          => [ 1; -1; 1 ]

     If X and Y are matrices, the cross product is applied along the
     first dimension with 3 elements. The optional argument DIM is used
     to force the cross product to be calculated along the dimension
     defined by DIM.

 -- Function File:  commutation_matrix (M, N)
     Return the commutation matrix  K(m,n)  which is the unique M*N by
     M*N  matrix such that K(m,n) * vec(A) = vec(A')  for all m by n
     matrices A.

     If only one argument M is given, K(m,m)  is returned.

     See Magnus and Neudecker (1988), Matrix differential calculus with
     applications in statistics and econometrics.

 -- Function File:  duplication_matrix (N)
     Return the duplication matrix Dn  which is the unique n^2 by
     n*(n+1)/2  matrix such that Dn vech (A) = vec (A)  for all
     symmetric n by n  matrices A.

     See Magnus and Neudecker (1988), Matrix differential calculus with
     applications in statistics and econometrics.


File: octave.info,  Node: Coordinate Transformations,  Next: Mathematical Constants,  Prev: Special Functions,  Up: Arithmetic

17.6 Coordinate Transformations
===============================

 -- Function File: [THETA, R] = cart2pol (X, Y)
 -- Function File: [THETA, R, Z] = cart2pol (X, Y, Z)
     Transform cartesian to polar or cylindrical coordinates.  X, Y
     (and Z) must be of same shape.  THETA describes the angle relative
     to the x - axis.  R is the distance to the z - axis (0, 0, z).

     *See also:* pol2cart, cart2sph, sph2cart.

 -- Function File: [X, Y] = pol2cart (THETA, R)
 -- Function File: [X, Y, Z] = pol2cart (THETA, R, Z)
     Transform polar or cylindrical to cartesian coordinates.  THETA, R
     (and Z) must be of same shape.  THETA describes the angle relative
     to the x - axis.  R is the distance to the z - axis (0, 0, z).

     *See also:* cart2pol, cart2sph, sph2cart.

 -- Function File: [THETA, PHI, R] = cart2sph (X, Y, Z)
     Transform cartesian to spherical coordinates.  X, Y and Z must be
     of same shape.  THETA describes the angle relative to the x - axis.
     PHI is the angle relative to the xy - plane.  R is the distance to
     the origin (0, 0, 0).

     *See also:* pol2cart, cart2pol, sph2cart.

 -- Function File: [X, Y, Z] = sph2cart (THETA, PHI, R)
     Transform spherical to cartesian coordinates.  X, Y and Z must be
     of same shape.  THETA describes the angle relative to the x-axis.
     PHI is the angle relative to the xy-plane.  R is the distance to
     the origin (0, 0, 0).

     *See also:* pol2cart, cart2pol, cart2sph.


File: octave.info,  Node: Mathematical Constants,  Prev: Coordinate Transformations,  Up: Arithmetic

17.7 Mathematical Constants
===========================

 -- Built-in Function:  I (X)
 -- Built-in Function:  I (N, M)
 -- Built-in Function:  I (N, M, K, ...)
 -- Built-in Function:  I (..., CLASS)
     Return a matrix or N-dimensional array whose elements are all equal
     to the pure imaginary unit, defined as   `sqrt (-1)'.  Since I
     (also i, J, and j) is a function, you can use the name(s) for
     other purposes.

 -- Built-in Function:  Inf (X)
 -- Built-in Function:  Inf (N, M)
 -- Built-in Function:  Inf (N, M, K, ...)
 -- Built-in Function:  Inf (..., CLASS)
     Return a matrix or N-dimensional array whose elements are all
     Infinity.  The arguments are handled the same as the arguments for
     `eye'.  The optional argument CLASS may be either `"single"' or
     `"double"'.  The default is `"double"'.

 -- Built-in Function:  NaN (X)
 -- Built-in Function:  NaN (N, M)
 -- Built-in Function:  NaN (N, M, K, ...)
 -- Built-in Function:  NaN (..., CLASS)
     Return a matrix or N-dimensional array whose elements are all NaN
     (Not a Number).  The value NaN is the result of an operation like
     0/0, or `Inf - Inf', or any operation with a NaN.

     Note that NaN always compares not equal to NaN.  This behavior is
     specified by the IEEE standard for floating point arithmetic.  To
     find NaN values, you must use the `isnan' function.

     The arguments are handled the same as the arguments for `eye'.
     The optional argument CLASS may be either `"single"' or
     `"double"'.  The default is `"double"'.

 -- Built-in Function:  pi (X)
 -- Built-in Function:  pi (N, M)
 -- Built-in Function:  pi (N, M, K, ...)
 -- Built-in Function:  pi (..., CLASS)
     Return a matrix or N-dimensional array whose elements are all equal
     to the ratio of the circumference of a circle to its diameter.
     Internally, `pi' is computed as `4.0 * atan (1.0)'.

 -- Built-in Function:  e (X)
 -- Built-in Function:  e (N, M)
 -- Built-in Function:  e (N, M, K, ...)
 -- Built-in Function:  e (..., CLASS)
     Return a matrix or N-dimensional array whose elements are all equal
     to the base of natural logarithms.  The constant  E  satisfies the
     equation  `log' (E) = 1.

 -- Built-in Function:  eps (X)
 -- Built-in Function:  eps (N, M)
 -- Built-in Function:  eps (N, M, K, ...)
 -- Built-in Function:  eps (..., CLASS)
     Return a matrix or N-dimensional array whose elements are all eps,
     the machine precision.  More precisely, `eps' is the largest
     relative spacing between any two adjacent numbers in the machine's
     floating point system.  This number is obviously system-dependent.
     On machines that support 64 bit IEEE floating point arithmetic,
     `eps' is approximately  2.2204e-16.

 -- Built-in Function:  realmax (X)
 -- Built-in Function:  realmax (N, M)
 -- Built-in Function:  realmax (N, M, K, ...)
 -- Built-in Function:  realmax (..., CLASS)
     Return a matrix or N-dimensional array whose elements are all equal
     to the largest floating point number that is representable.  The
     actual value is system-dependent.  On machines that support 64-bit
     IEEE floating point arithmetic, `realmax' is approximately
     1.7977e+308

     *See also:* realmin.

 -- Built-in Function:  realmin (X)
 -- Built-in Function:  realmin (N, M)
 -- Built-in Function:  realmin (N, M, K, ...)
 -- Built-in Function:  realmin (..., CLASS)
     Return a matrix or N-dimensional array whose elements are all equal
     to the smallest normalized floating point number that is
     representable.  The actual value is system-dependent.  On machines
     that support 64-bit IEEE floating point arithmetic, `realmin' is
     approximately  2.2251e-308

     *See also:* realmax.


File: octave.info,  Node: Linear Algebra,  Next: Nonlinear Equations,  Prev: Arithmetic,  Up: Top

18 Linear Algebra
*****************

This chapter documents the linear algebra functions of Octave.
Reference material for many of these functions may be found in Golub
and Van Loan, `Matrix Computations, 2nd Ed.', Johns Hopkins, 1989, and
in `LAPACK Users' Guide', SIAM, 1992.

* Menu:

* Techniques used for Linear Algebra::
* Basic Matrix Functions::
* Matrix Factorizations::
* Functions of a Matrix::


File: octave.info,  Node: Techniques used for Linear Algebra,  Next: Basic Matrix Functions,  Up: Linear Algebra

18.1 Techniques used for Linear Algebra
=======================================

Octave includes a poly-morphic solver, that selects an appropriate
matrix factorization depending on the properties of the matrix itself.
Generally, the cost of determining the matrix type is small relative to
the cost of factorizing the matrix itself, but in any case the matrix
type is cached once it is calculated, so that it is not re-determined
each time it is used in a linear equation.

   The selection tree for how the linear equation is solve or a matrix
inverse is form is given by

  1. If the matrix is upper or lower triangular sparse a forward or
     backward substitution using the LAPACK xTRTRS function, and goto 4.

  2. If the matrix is square, hermitian with a real positive diagonal,
     attempt Cholesky factorization using the LAPACK xPOTRF function.

  3. If the Cholesky factorization failed or the matrix is not
     hermitian with a real positive diagonal, and the matrix is square,
     factorize using the LAPACK xGETRF function.

  4. If the matrix is not square, or any of the previous solvers flags
     a singular or near singular matrix, find a least squares solution
     using the LAPACK xGELSD function.

   The user can force the type of the matrix with the `matrix_type'
function. This overcomes the cost of discovering the type of the matrix.
However, it should be noted incorrectly identifying the type of the
matrix will lead to unpredictable results, and so `matrix_type' should
be used with care.

   It should be noted that the test for whether a matrix is a candidate
for Cholesky factorization, performed above and by the `matrix_type'
function, does not give a certainty that the matrix is Hermitian.
However, the attempt to factorize the matrix will quickly flag a
non-Hermitian matrix.


File: octave.info,  Node: Basic Matrix Functions,  Next: Matrix Factorizations,  Prev: Techniques used for Linear Algebra,  Up: Linear Algebra

18.2 Basic Matrix Functions
===========================

 -- Loadable Function: AA = balance (A, OPT)
 -- Loadable Function: [DD, AA] = balance (A, OPT)
 -- Loadable Function: [CC, DD, AA, BB] = balance (A, B, OPT)
     Compute `aa = dd \ a * dd' in which `aa' is a matrix whose row and
     column norms are roughly equal in magnitude, and `dd' = `p * d',
     in which `p' is a permutation matrix and `d' is a diagonal matrix
     of powers of two.  This allows the equilibration to be computed
     without roundoff.  Results of eigenvalue calculation are typically
     improved by balancing first.

     If four output values are requested, compute `aa = cc*a*dd' and
     `bb = cc*b*dd)', in which `aa' and `bb' have non-zero elements of
     approximately the same magnitude and `cc' and `dd' are permuted
     diagonal matrices as in `dd' for the algebraic eigenvalue problem.

     The eigenvalue balancing option `opt' may be one of:

    `"N"', `"n"'
          No balancing; arguments copied, transformation(s) set to
          identity.

    `"P"', `"p"'
          Permute argument(s) to isolate eigenvalues where possible.

    `"S"', `"s"'
          Scale to improve accuracy of computed eigenvalues.

    `"B"', `"b"'
          Permute and scale, in that order. Rows/columns of a (and b)
          that are isolated by permutation are not scaled.  This is the
          default behavior.

     Algebraic eigenvalue balancing uses standard LAPACK routines.

     Generalized eigenvalue problem balancing uses Ward's algorithm
     (SIAM Journal on Scientific and Statistical Computing, 1981).

 -- Function File:  cond (A,P)
     Compute the P-norm condition number of a matrix. `cond (A)' is
     defined as `norm (A, P) * norm (inv (A), P)'.  By default `P=2' is
     used which implies a (relatively slow) singular value
     decomposition. Other possible selections are `P= 1, Inf, inf,
     'Inf', 'fro'' which are generally faster.

     *See also:* norm, inv, det, svd, rank.

 -- Loadable Function: [D, RCOND] =  det (A)
     Compute the determinant of A using LAPACK.  Return an estimate of
     the reciprocal condition number if requested.

 -- Function File:  dmult (A, B)
     If A is a vector of length `rows (B)', return `diag (A) * B' (but
     computed much more efficiently).

 -- Function File:  dot (X, Y, DIM)
     Computes the dot product of two vectors. If X and Y are matrices,
     calculate the dot-product along the first non-singleton dimension.
     If the optional argument DIM is given, calculate the dot-product
     along this dimension.

 -- Loadable Function: LAMBDA = eig (A)
 -- Loadable Function: [V, LAMBDA] = eig (A)
     The eigenvalues (and eigenvectors) of a matrix are computed in a
     several step process which begins with a Hessenberg decomposition,
     followed by a Schur decomposition, from which the eigenvalues are
     apparent.  The eigenvectors, when desired, are computed by further
     manipulations of the Schur decomposition.

     The eigenvalues returned by `eig' are not ordered.

 -- Loadable Function: G = givens (X, Y)
 -- Loadable Function: [C, S] = givens (X, Y)
     Return a 2 by 2 orthogonal matrix `G = [C S; -S' C]' such that `G
     [X; Y] = [*; 0]' with X and Y scalars.

     For example,

          givens (1, 1)
               =>   0.70711   0.70711
                   -0.70711   0.70711

 -- Loadable Function: [X, RCOND] =  inv (A)
 -- Loadable Function: [X, RCOND] =  inverse (A)
     Compute the inverse of the square matrix A.  Return an estimate of
     the reciprocal condition number if requested, otherwise warn of an
     ill-conditioned matrix if the reciprocal condition number is small.

 -- Loadable Function: TYPE = matrix_type (A)
 -- Loadable Function: A = matrix_type (A, TYPE)
 -- Loadable Function: A = matrix_type (A, 'upper', PERM)
 -- Loadable Function: A = matrix_type (A, 'lower', PERM)
 -- Loadable Function: A = matrix_type (A, 'banded', NL, NU)
     Identify the matrix type or mark a matrix as a particular type.
     This allows rapid for solutions of linear equations involving A to
     be performed. Called with a single argument, `matrix_type' returns
     the type of the matrix and caches it for future use. Called with
     more than one argument, `matrix_type' allows the type of the
     matrix to be defined.

     The possible matrix types depend on whether the matrix is full or
     sparse, and can be one of the following

    'unknown'
          Remove any previously cached matrix type, and mark type as
          unknown

    'full'
          Mark the matrix as full.

    'positive definite'
          Probable full positive definite matrix.

    'diagonal'
          Diagonal Matrix. (Sparse matrices only)

    'permuted diagonal'
          Permuted Diagonal matrix. The permutation does not need to be
          specifically indicated, as the structure of the matrix
          explicitly gives this. (Sparse matrices only)

    'upper'
          Upper triangular. If the optional third argument PERM is
          given, the matrix is assumed to be a permuted upper
          triangular with the permutations defined by the vector PERM.

    'lower'
          Lower triangular. If the optional third argument PERM is
          given, the matrix is assumed to be a permuted lower
          triangular with the permutations defined by the vector PERM.

    'banded'
    'banded positive definite'
          Banded matrix with the band size of NL below the diagonal and
          NU above it. If NL and NU are 1, then the matrix is
          tridiagonal and treated with specialized code. In addition
          the matrix can be marked as probably a positive definite
          (Sparse matrices only)

    'singular'
          The matrix is assumed to be singular and will be treated with
          a minimum norm solution


     Note that the matrix type will be discovered automatically on the
     first attempt to solve a linear equation involving A. Therefore
     `matrix_type' is only useful to give Octave hints of the matrix
     type. Incorrectly defining the matrix type will result in
     incorrect results from solutions of linear equations, and so it is
     entirely the responsibility of the user to correctly identify the
     matrix type.

     Also the test for positive definiteness is a low cost test for a
     hermitian matrix with a real positive diagonal. This does not
     guarantee that the matrix is positive definite, but only that it
     is a probable candidate. When such a matrix is factorized, a
     Cholesky factorization is first attempted, and if that fails the
     matrix is then treated with an LU factorization. Once the matrix
     has been factorized, `matrix_type' will return the correct
     classification of the matrix.

 -- Function File:  norm (A, P)
     Compute the p-norm of the matrix A.  If the second argument is
     missing, `p = 2' is assumed.

     If A is a matrix:

    P = `1'
          1-norm, the largest column sum of the absolute values of A.

    P = `2'
          Largest singular value of A.

    P = `Inf' or `"inf"'
          Infinity norm, the largest row sum of the absolute values of
          A.

    P = `"fro"'
          Frobenius norm of A, `sqrt (sum (diag (A' * A)))'.

     If A is a vector or a scalar:

    P = `Inf' or `"inf"'
          `max (abs (A))'.

    P = `-Inf'
          `min (abs (A))'.

    P = `"fro"'
          Frobenius norm of A, `sqrt (sumsq (abs (a)))'.

    other
          p-norm of A, `(sum (abs (A) .^ P)) ^ (1/P)'.


     *See also:* cond, svd.

 -- Function File:  null (A, TOL)
     Return an orthonormal basis of the null space of A.

     The dimension of the null space is taken as the number of singular
     values of A not greater than TOL.  If the argument TOL is missing,
     it is computed as

          max (size (A)) * max (svd (A)) * eps

 -- Function File:  orth (A, TOL)
     Return an orthonormal basis of the range space of A.

     The dimension of the range space is taken as the number of singular
     values of A greater than TOL.  If the argument TOL is missing, it
     is computed as

          max (size (A)) * max (svd (A)) * eps

 -- Loadable Function:  pinv (X, TOL)
     Return the pseudoinverse of X.  Singular values less than TOL are
     ignored.

     If the second argument is omitted, it is assumed that

          tol = max (size (X)) * sigma_max (X) * eps,

     where `sigma_max (X)' is the maximal singular value of X.

 -- Function File:  rank (A, TOL)
     Compute the rank of A, using the singular value decomposition.
     The rank is taken to be the number  of singular values of A that
     are greater than the specified tolerance TOL.  If the second
     argument is omitted, it is taken to be

          tol = max (size (A)) * sigma(1) * eps;

     where `eps' is machine precision and `sigma(1)' is the largest
     singular value of A.

 -- Function File:  trace (A)
     Compute the trace of A, `sum (diag (A))'.

 -- Function File: [R, K] = rref (A, TOL)
     Returns the reduced row echelon form of A. TOL defaults to `eps *
     max (size (A)) * norm (A, inf)'.

     Called with two return arguments, K returns the vector of "bound
     variables", which are those columns on which elimination has been
     performed.



File: octave.info,  Node: Matrix Factorizations,  Next: Functions of a Matrix,  Prev: Basic Matrix Functions,  Up: Linear Algebra

18.3 Matrix Factorizations
==========================

 -- Loadable Function:  chol (A)
     Compute the Cholesky factor, R, of the symmetric positive definite
     matrix A, where

          r' * r = a.


     *See also:* cholinv, chol2inv.

 -- Loadable Function:  cholinv (A)
     Use the Cholesky factorization to compute the inverse of the
     symmetric positive definite matrix A.

     *See also:* chol, chol2inv.

 -- Loadable Function:  chol2inv (U)
     Invert a symmetric, positive definite square matrix from its
     Cholesky decomposition, U.  Note that U should be an
     upper-triangular matrix with positive diagonal elements.
     `chol2inv (U)' provides `inv (U'*U)' but it is much faster than
     using `inv'.

     *See also:* chol, cholinv.

 -- Loadable Function: H = hess (A)
 -- Loadable Function: [P, H] = hess (A)
     Compute the Hessenberg decomposition of the matrix A.

     The Hessenberg decomposition is usually used as the first step in
     an eigenvalue computation, but has other applications as well (see
     Golub, Nash, and Van Loan, IEEE Transactions on Automatic Control,
     1979).  The Hessenberg decomposition is `p * h * p' = a' where `p'
     is a square unitary matrix (`p' * p = I', using complex-conjugate
     transposition) and `h' is upper Hessenberg (`i >= j+1 => h (i, j)
     = 0').

 -- Loadable Function: [L, U, P] = lu (A)
     Compute the LU decomposition of A, using subroutines from LAPACK.
     The result is returned in a permuted form, according to the
     optional return value P.  For example, given the matrix `a = [1,
     2; 3, 4]',

          [l, u, p] = lu (a)

     returns

          l =

            1.00000  0.00000
            0.33333  1.00000

          u =

            3.00000  4.00000
            0.00000  0.66667

          p =

            0  1
            1  0

     The matrix is not required to be square.

 -- Loadable Function: [Q, R, P] = qr (A)
     Compute the QR factorization of A, using standard LAPACK
     subroutines.  For example, given the matrix `a = [1, 2; 3, 4]',

          [q, r] = qr (a)

     returns

          q =

            -0.31623  -0.94868
            -0.94868   0.31623

          r =

            -3.16228  -4.42719
             0.00000  -0.63246

     The `qr' factorization has applications in the solution of least
     squares problems

          `min norm(A x - b)'

     for overdetermined systems of equations (i.e., `a'  is a tall,
     thin matrix).  The QR factorization is `q * r = a' where `q' is an
     orthogonal matrix and `r' is upper triangular.

     The permuted QR factorization `[Q, R, P] = qr (A)' forms the QR
     factorization such that the diagonal entries of `r' are decreasing
     in magnitude order.  For example, given the matrix `a = [1, 2; 3,
     4]',

          [q, r, p] = qr(a)

     returns

          q =

            -0.44721  -0.89443
            -0.89443   0.44721

          r =

            -4.47214  -3.13050
             0.00000   0.44721

          p =

             0  1
             1  0

     The permuted `qr' factorization `[q, r, p] = qr (a)' factorization
     allows the construction of an orthogonal basis of `span (a)'.

 -- Loadable Function: LAMBDA = qz (A, B)
     Generalized eigenvalue problem A x = s B x, QZ decomposition.
     There are three ways to call this function:
       1. `lambda = qz(A,B)'

          Computes the generalized eigenvalues LAMBDA of (A - s B).

       2. `[AA, BB, Q, Z, V, W, lambda] = qz (A, B)'

          Computes qz decomposition, generalized eigenvectors, and
          generalized eigenvalues of (A - sB)

                   A*V = B*V*diag(lambda)
                   W'*A = diag(lambda)*W'*B
                   AA = Q'*A*Z, BB = Q'*B*Z
          with Q and Z orthogonal (unitary)= I

       3. `[AA,BB,Z{, lambda}] = qz(A,B,opt)'

          As in form [2], but allows ordering of generalized eigenpairs
          for (e.g.) solution of discrete time algebraic Riccati
          equations.  Form 3 is not available for complex matrices, and
          does not compute the generalized eigenvectors V, W, nor the
          orthogonal matrix Q.
         OPT
               for ordering eigenvalues of the GEP pencil.  The leading
               block of the revised pencil contains all eigenvalues
               that satisfy:
              `"N"'
                    = unordered (default)

              `"S"'
                    = small: leading block has all |lambda| <=1

              `"B"'
                    = big: leading block has all |lambda| >= 1

              `"-"'
                    = negative real part: leading block has all
                    eigenvalues in the open left half-plane

              `"+"'
                    = nonnegative real part: leading block has all
                    eigenvalues in the closed right half-plane

     Note: qz performs permutation balancing, but not scaling (see
     balance).  Order of output arguments was selected for
     compatibility with MATLAB


     *See also:* balance, dare, eig, schur.

 -- Function File: [AA, BB, Q, Z] = qzhess (A, B)
     Compute the Hessenberg-triangular decomposition of the matrix
     pencil `(A, B)', returning `AA = Q * A * Z', `BB = Q * B * Z',
     with Q and Z orthogonal.  For example,

          [aa, bb, q, z] = qzhess ([1, 2; 3, 4], [5, 6; 7, 8])
          => aa = [ -3.02244, -4.41741;  0.92998,  0.69749 ]
          => bb = [ -8.60233, -9.99730;  0.00000, -0.23250 ]
          =>  q = [ -0.58124, -0.81373; -0.81373,  0.58124 ]
          =>  z = [ 1, 0; 0, 1 ]

     The Hessenberg-triangular decomposition is the first step in Moler
     and Stewart's QZ decomposition algorithm.

     Algorithm taken from Golub and Van Loan, `Matrix Computations, 2nd
     edition'.

 -- Loadable Function: S = schur (A)
 -- Loadable Function: [U, S] = schur (A, OPT)
     The Schur decomposition is used to compute eigenvalues of a square
     matrix, and has applications in the solution of algebraic Riccati
     equations in control (see `are' and `dare').  `schur' always
     returns `s = u' * a * u' where `u'  is a unitary matrix (`u'* u'
     is identity) and `s' is upper triangular.  The eigenvalues of `a'
     (and `s') are the diagonal elements of `s'.  If the matrix `a' is
     real, then the real Schur decomposition is computed, in which the
     matrix `u' is orthogonal and `s' is block upper triangular with
     blocks of size at most `2 x 2' along the diagonal.  The diagonal
     elements of `s' (or the eigenvalues of the `2 x 2' blocks, when
     appropriate) are the eigenvalues of `a' and `s'.

     The eigenvalues are optionally ordered along the diagonal
     according to the value of `opt'.  `opt = "a"' indicates that all
     eigenvalues with negative real parts should be moved to the leading
     block of `s' (used in `are'), `opt = "d"' indicates that all
     eigenvalues with magnitude less than one should be moved to the
     leading block of `s' (used in `dare'), and `opt = "u"', the
     default, indicates that no ordering of eigenvalues should occur.
     The leading `k' columns of `u' always span the `a'-invariant
     subspace corresponding to the `k' leading eigenvalues of `s'.

 -- Loadable Function: S = svd (A)
 -- Loadable Function: [U, S, V] = svd (A)
     Compute the singular value decomposition of A

          A = U*S*V'

     The function `svd' normally returns the vector of singular values.
     If asked for three return values, it computes U, S, and V.  For
     example,

          svd (hilb (3))

     returns

          ans =

            1.4083189
            0.1223271
            0.0026873

     and

          [u, s, v] = svd (hilb (3))

     returns

          u =

            -0.82704   0.54745   0.12766
            -0.45986  -0.52829  -0.71375
            -0.32330  -0.64901   0.68867

          s =

            1.40832  0.00000  0.00000
            0.00000  0.12233  0.00000
            0.00000  0.00000  0.00269

          v =

            -0.82704   0.54745   0.12766
            -0.45986  -0.52829  -0.71375
            -0.32330  -0.64901   0.68867

     If given a second argument, `svd' returns an economy-sized
     decomposition, eliminating the unnecessary rows or columns of U or
     V.

 -- Function File: [HOUSV, BETA, ZER] = housh (X, J, Z)
     Compute Householder reflection vector HOUSV to reflect X to be the
     jth column of identity, i.e.,

          (I - beta*housv*housv')x =  norm(x)*e(j) if x(1) < 0,
          (I - beta*housv*housv')x = -norm(x)*e(j) if x(1) >= 0

     Inputs

    X
          vector

    J
          index into vector

    Z
          threshold for zero  (usually should be the number 0)

     Outputs (see Golub and Van Loan):

    BETA
          If beta = 0, then no reflection need be applied (zer set to 0)

    HOUSV
          householder vector

 -- Function File: [U, H, NU] = krylov (A, V, K, EPS1, PFLG)
     Construct an orthogonal basis U of block Krylov subspace

          [v a*v a^2*v ... a^(k+1)*v]

     Using Householder reflections to guard against loss of
     orthogonality.

     If V is a vector, then H contains the Hessenberg matrix such that
     `a*u == u*h+rk*ek'', in which `rk = a*u(:,k)-u*h(:,k)', and `ek''
     is the vector `[0, 0, ..., 1]' of length `k'.  Otherwise, H is
     meaningless.

     If V is a vector and K is greater than `length(A)-1', then H
     contains the Hessenberg matrix such that `a*u == u*h'.

     The value of NU is the dimension of the span of the krylov
     subspace (based on EPS1).

     If B is a vector and K is greater than M-1, then H contains the
     Hessenberg decomposition of A.

     The optional parameter EPS1 is the threshold for zero.  The
     default value is 1e-12.

     If the optional parameter PFLG is nonzero, row pivoting is used to
     improve numerical behavior.  The default value is 0.

     Reference: Hodel and Misra, "Partial Pivoting in the Computation of
     Krylov Subspaces", to be submitted to Linear Algebra and its
     Applications


File: octave.info,  Node: Functions of a Matrix,  Prev: Matrix Factorizations,  Up: Linear Algebra

18.4 Functions of a Matrix
==========================

 -- Loadable Function:  expm (A)
     Return the exponential of a matrix, defined as the infinite Taylor
     series

          expm(a) = I + a + a^2/2! + a^3/3! + ...

     The Taylor series is _not_ the way to compute the matrix
     exponential; see Moler and Van Loan, `Nineteen Dubious Ways to
     Compute the Exponential of a Matrix', SIAM Review, 1978.  This
     routine uses Ward's diagonal Pade' approximation method with three
     step preconditioning (SIAM Journal on Numerical Analysis, 1977).
     Diagonal Pade'  approximations are rational polynomials of matrices

               -1
          D (a)   N (a)

     whose Taylor series matches the first `2q+1' terms of the Taylor
     series above; direct evaluation of the Taylor series (with the
     same preconditioning steps) may be desirable in lieu of the Pade'
     approximation when `Dq(a)' is ill-conditioned.

 -- Function File:  logm (A)
     Compute the matrix logarithm of the square matrix A.  Note that
     this is currently implemented in terms of an eigenvalue expansion
     and needs to be improved to be more robust.

 -- Loadable Function: [RESULT, ERROR_ESTIMATE] = sqrtm (A)
     Compute the matrix square root of the square matrix A.

     Ref: Nicholas J. Higham. A new sqrtm for MATLAB. Numerical Analysis
     Report No. 336, Manchester Centre for Computational Mathematics,
     Manchester, England, January 1999.

     *See also:* expm, logm, funm.

 -- Loadable Function:  kron (A, B)
     Form the kronecker product of two matrices, defined block by block
     as

          x = [a(i, j) b]

     For example,

          kron (1:4, ones (3, 1))
                =>  1  2  3  4
                    1  2  3  4
                    1  2  3  4

 -- Loadable Function: X = syl (A, B, C)
     Solve the Sylvester equation

          A X + X B + C = 0
     using standard LAPACK subroutines.  For example,

          syl ([1, 2; 3, 4], [5, 6; 7, 8], [9, 10; 11, 12])
               => [ -0.50000, -0.66667; -0.66667, -0.50000 ]


File: octave.info,  Node: Nonlinear Equations,  Next: Sparse Matrices,  Prev: Linear Algebra,  Up: Top

19 Nonlinear Equations
**********************

Octave can solve sets of nonlinear equations of the form

     F (x) = 0

using the function `fsolve', which is based on the MINPACK subroutine
`hybrd'.  This is an iterative technique so a starting point will have
to be provided.  This also has the consequence that convergence is not
guaranteed even if a solution exists.

 -- Loadable Function: [X, FVAL, INFO] = fsolve (FCN, X0)
     Given FCN, the name of a function of the form `f (X)' and an
     initial starting point X0, `fsolve' solves the set of equations
     such that `f(X) == 0'.

     On return, FVAL contains the value of the function FCN evaluated
     at X, and INFO may be one of the following values:

    -2
          Invalid input parameters.

    -1
          Error in user-supplied function.

    1
          Relative error between two consecutive iterates is at most the
          specified tolerance (see `fsolve_options').

    3
          Algorithm failed to converge.

    4
          Limit on number of function calls reached.

     If FCN is a two-element string array, or a two element cell array
     containing either the function name or inline or function handle.
     The first element names the function f described above, and the
     second element names a function of the form `j (X)' to compute the
     Jacobian matrix with elements

                     df_i
          jac(i,j) = ----
                     dx_j

     You can use the function `fsolve_options' to set optional
     parameters for `fsolve'.

 -- Loadable Function:  fsolve_options (OPT, VAL)
     When called with two arguments, this function allows you set
     options parameters for the function `fsolve'.  Given one argument,
     `fsolve_options' returns the value of the corresponding option.  If
     no arguments are supplied, the names of all the available options
     and their current values are displayed.

     Options include

    `"tolerance"'
          Nonnegative relative tolerance.

   Here is a complete example.  To solve the set of equations

     -2x^2 + 3xy   + 4 sin(y) = 6
      3x^2 - 2xy^2 + 3 cos(x) = -4

you first need to write a function to compute the value of the given
function.  For example:

     function y = f (x)
       y(1) = -2*x(1)^2 + 3*x(1)*x(2)   + 4*sin(x(2)) - 6;
       y(2) =  3*x(1)^2 - 2*x(1)*x(2)^2 + 3*cos(x(1)) + 4;
     endfunction

   Then, call `fsolve' with a specified initial condition to find the
roots of the system of equations.  For example, given the function `f'
defined above,

     [x, fval, info] = fsolve (@f, [1; 2])

results in the solution

     x =

       0.57983
       2.54621

     fval =

       -5.7184e-10
        5.5460e-10

     info = 1

A value of `info = 1' indicates that the solution has converged.

   The function `perror' may be used to print English messages
corresponding to the numeric error codes.  For example,

     perror ("fsolve", 1)
          -| solution converged to requested tolerance

   When no Jacobian is supplied (as in the example above) it is
approximated numerically.  This requires more function evaluations, and
hence is less efficient.  In the example above we could compute the
Jacobian analytically as

     function J = jacobian(x)
       J(1,1) =  3*x(2) - 4*x(1);
       J(1,2) =  4*cos(x(2)) + 3*x(1);
       J(2,1) = -2*x(2)^2 - 3*sin(x(1)) + 6*x(1);
       J(2,2) = -4*x(1)*x(2);
     endfunction

Using this Jacobian is done with the following code

     [x, fval, info] = fsolve ({@f, @jacobian}, [1; 2]);

which gives the same solution as before.


File: octave.info,  Node: Sparse Matrices,  Next: Numerical Integration,  Prev: Nonlinear Equations,  Up: Top

20 Sparse Matrices
******************

* Menu:

* Basics:: The Creation and Manipulation of Sparse Matrices
* Sparse Linear Algebra:: Linear Algebra on Sparse Matrices
* Iterative Techniques:: Iterative Techniques applied to Sparse Matrices
* Real Life Example:: Real Life Example of the use of Sparse Matrices


File: octave.info,  Node: Basics,  Next: Sparse Linear Algebra,  Prev: Sparse Matrices,  Up: Sparse Matrices

20.1 The Creation and Manipulation of Sparse Matrices
=====================================================

The size of mathematical problems that can be treated at any particular
time is generally limited by the available computing resources. Both,
the speed of the computer and its available memory place limitation on
the problem size.

   There are many classes of mathematical problems which give rise to
matrices, where a large number of the elements are zero. In this case
it makes sense to have a special matrix type to handle this class of
problems where only the non-zero elements of the matrix are stored. Not
only does this reduce the amount of memory to store the matrix, but it
also means that operations on this type of matrix can take advantage of
the a-priori knowledge of the positions of the non-zero elements to
accelerate their calculations.

   A matrix type that stores only the non-zero elements is generally
called sparse. It is the purpose of this document to discuss the basics
of the storage and creation of sparse matrices and the fundamental
operations on them.

* Menu:

* Storage:: Storage of Sparse Matrices
* Creation:: Creating Sparse Matrices
* Information:: Finding out Information about Sparse Matrices
* Operators and Functions:: Basic Operators and Functions on Sparse Matrices


File: octave.info,  Node: Storage,  Next: Creation,  Prev: Basics,  Up: Basics

20.1.1 Storage of Sparse Matrices
---------------------------------

It is not strictly speaking necessary for the user to understand how
sparse matrices are stored. However, such an understanding will help to
get an understanding of the size of sparse matrices. Understanding the
storage technique is also necessary for those users wishing to create
their own oct-files.

   There are many different means of storing sparse matrix data. What
all of the methods have in common is that they attempt to reduce the
complexity and storage given a-priori knowledge of the particular class
of problems that will be solved. A good summary of the available
techniques for storing sparse matrix is given by Saad (1).  With full
matrices, knowledge of the point of an element of the matrix within the
matrix is implied by its position in the computers memory.  However,
this is not the case for sparse matrices, and so the positions of the
non-zero elements of the matrix must equally be stored.

   An obvious way to do this is by storing the elements of the matrix as
triplets, with two elements being their position in the array (rows and
column) and the third being the data itself. This is conceptually easy
to grasp, but requires more storage than is strictly needed.

   The storage technique used within Octave is the compressed column
format.  In this format the position of each element in a row and the
data are stored as previously. However, if we assume that all elements
in the same column are stored adjacent in the computers memory, then we
only need to store information on the number of non-zero elements in
each column, rather than their positions. Thus assuming that the matrix
has more non-zero elements than there are columns in the matrix, we win
in terms of the amount of memory used.

   In fact, the column index contains one more element than the number
of columns, with the first element always being zero. The advantage of
this is a simplification in the code, in that there is no special case
for the first or last columns. A short example, demonstrating this in C
is.

       for (j = 0; j < nc; j++)
         for (i = cidx (j); i < cidx(j+1); i++)
            printf ("non-zero element (%i,%i) is %d\n",
     	   ridx(i), j, data(i));

   A clear understanding might be had by considering an example of how
the above applies to an example matrix. Consider the matrix

         1   2   0  0
         0   0   0  3
         0   0   0  4

   The non-zero elements of this matrix are

        (1, 1)  => 1
        (1, 2)  => 2
        (2, 4)  => 3
        (3, 4)  => 4

   This will be stored as three vectors CIDX, RIDX and DATA,
representing the column indexing, row indexing and data respectively.
The contents of these three vectors for the above matrix will be

       CIDX = [0, 1, 2, 2, 4]
       RIDX = [0, 0, 1, 2]
       DATA = [1, 2, 3, 4]

   Note that this is the representation of these elements with the
first row and column assumed to start at zero, while in Octave itself
the row and column indexing starts at one. Thus the number of elements
in the I-th column is given by `CIDX (I + 1) - CIDX (I)'.

   Although Octave uses a compressed column format, it should be noted
that compressed row formats are equally possible. However, in the
context of mixed operations between mixed sparse and dense matrices, it
makes sense that the elements of the sparse matrices are in the same
order as the dense matrices. Octave stores dense matrices in column
major ordering, and so sparse matrices are equally stored in this
manner.

   A further constraint on the sparse matrix storage used by Octave is
that all elements in the rows are stored in increasing order of their
row index, which makes certain operations faster. However, it imposes
the need to sort the elements on the creation of sparse matrices. Having
disordered elements is potentially an advantage in that it makes
operations such as concatenating two sparse matrices together easier
and faster, however it adds complexity and speed problems elsewhere.

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

   (1) Youcef Saad "SPARSKIT: A basic toolkit for sparse matrix
computation", 1994,
`http://www-users.cs.umn.edu/~saad/software/SPARSKIT/paper.ps'


File: octave.info,  Node: Creation,  Next: Information,  Prev: Storage,  Up: Basics

20.1.2 Creating Sparse Matrices
-------------------------------

There are several means to create sparse matrix.

Returned from a function
     There are many functions that directly return sparse matrices.
     These include "speye", "sprand", "spdiag", etc.

Constructed from matrices or vectors
     The function "sparse" allows a sparse matrix to be constructed from
     three vectors representing the row, column and data.
     Alternatively, the function "spconvert" uses a three column matrix
     format to allow easy importation of data from elsewhere.

Created and then filled
     The function "sparse" or "spalloc" can be used to create an empty
     matrix that is then filled by the user

From a user binary program
     The user can directly create the sparse matrix within an oct-file.

   There are several basic functions to return specific sparse
matrices. For example the sparse identity matrix, is a matrix that is
often needed. It therefore has its own function to create it as `speye
(N)' or `speye (R, C)', which creates an N-by-N or R-by-C sparse
identity matrix.

   Another typical sparse matrix that is often needed is a random
distribution of random elements. The functions "sprand" and "sprandn"
perform this for uniform and normal random distributions of elements.
They have exactly the same calling convention, where `sprand (R, C, D)',
creates an R-by-C sparse matrix with a density of filled elements of D.

   Other functions of interest that directly create sparse matrices, are
"spdiag" or its generalization "spdiags", that can take the definition
of the diagonals of the matrix and create the sparse matrix that
corresponds to this. For example

     s = spdiag (sparse(randn(1,n)), -1);

   creates a sparse (N+1)-by-(N+1) sparse matrix with a single diagonal
defined.

 -- Loadable Function:  spatan2 (Y, X)
     Compute atan (Y / X) for corresponding sparse matrix elements of Y
     and X.  The result is in range -pi to pi.

 -- Loadable Function: Y = spcumprod (X,DIM)
     Cumulative product of elements along dimension DIM.  If DIM is
     omitted, it defaults to 1 (column-wise cumulative products).

     *See also:* spcumsum.

 -- Loadable Function: Y = spcumsum (X,DIM)
     Cumulative sum of elements along dimension DIM.  If DIM is
     omitted, it defaults to 1 (column-wise cumulative sums).

     *See also:* spcumprod.

 -- Loadable Function:  spdiag (V, K)
     Return a diagonal matrix with the sparse vector V on diagonal K.
     The second argument is optional. If it is positive, the vector is
     placed on the K-th super-diagonal. If it is negative, it is placed
     on the -K-th sub-diagonal.  The default value of K is 0, and the
     vector is placed on the main diagonal.  For example,

          spdiag ([1, 2, 3], 1)
          ans =

          Compressed Column Sparse (rows=4, cols=4, nnz=3)
            (1 , 2) -> 1
            (2 , 3) -> 2
            (3 , 4) -> 3

     Given a matrix argument, instead of a vector, `spdiag' extracts the
     K-th diagonal of the sparse matrix.

     *See also:* diag.

 -- Function File: [B, C] = spdiags (A)
 -- Function File: B = spdiags (A, C)
 -- Function File: B = spdiags (V, C, A)
 -- Function File: B = spdiags (V, C, M, N)
     A generalization of the function `spdiag'. Called with a single
     input argument, the non-zero diagonals C of A are extracted.  With
     two arguments the diagonals to extract are given by the vector C.

     The other two forms of `spdiags' modify the input matrix by
     replacing the diagonals. They use the columns of V to replace the
     columns represented by the vector C. If the sparse matrix A is
     defined then the diagonals of this matrix are replaced.  Otherwise
     a matrix of M by N is created with the diagonals given by V.

     Negative values of C represent diagonals below the main diagonal,
     and positive values of C diagonals above the main diagonal.

     For example

          spdiags (reshape (1:12, 4, 3), [-1 0 1], 5, 4)
          =>    5 10  0  0
                1  6 11  0
                0  2  7 12
                0  0  3  8
                0  0  0  4


 -- Function File: Y = speye (M)
 -- Function File: Y = speye (M, N)
 -- Function File: Y = speye (SZ)
     Returns a sparse identity matrix. This is significantly more
     efficient than `sparse (eye (M))' as the full matrix is not
     constructed.

     Called with a single argument a square matrix of size M by M is
     created. Otherwise a matrix of M by N is created. If called with a
     single vector argument, this argument is taken to be the size of
     the matrix to create.

 -- Function File: Y = spfun (F,X)
     Compute `f(X)' for the non-zero values of X.  This results in a
     sparse matrix with the same structure as X. The function F can be
     passed as a string, a function handle or an inline function.

 -- Mapping Function:  spmax (X, Y, DIM)
 -- Mapping Function: [W, IW] = spmax (X)
     For a vector argument, return the maximum value.  For a matrix
     argument, return the maximum value from each column, as a row
     vector, or over the dimension DIM if defined. For two matrices (or
     a matrix and scalar), return the pair-wise maximum.  Thus,

          max (max (X))

     returns the largest element of X, and

          max (2:5, pi)
              =>  3.1416  3.1416  4.0000  5.0000
     compares each element of the range `2:5' with `pi', and
     returns a row vector of the maximum values.

     For complex arguments, the magnitude of the elements are used for
     comparison.

     If called with one input and two output arguments, `max' also
     returns the first index of the maximum value(s). Thus,

          [x, ix] = max ([1, 3, 5, 2, 5])
              =>  x = 5
                  ix = 3

 -- Mapping Function:  spmin (X, Y, DIM)
 -- Mapping Function: [W, IW] = spmin (X)
     For a vector argument, return the minimum value.  For a matrix
     argument, return the minimum value from each column, as a row
     vector, or over the dimension DIM if defined. For two matrices (or
     a matrix and scalar), return the pair-wise minimum.  Thus,

          min (min (X))

     returns the smallest element of X, and

          min (2:5, pi)
              =>  2.0000  3.0000  3.1416  3.1416
     compares each element of the range `2:5' with `pi', and
     returns a row vector of the minimum values.

     For complex arguments, the magnitude of the elements are used for
     comparison.

     If called with one input and two output arguments, `min' also
     returns the first index of the minimum value(s). Thus,

          [x, ix] = min ([1, 3, 0, 2, 5])
              =>  x = 0
                  ix = 3

 -- Function File: Y = spones (X)
     Replace the non-zero entries of X with ones. This creates a sparse
     matrix with the same structure as X.

 -- Loadable Function: Y = spprod (X,DIM)
     Product of elements along dimension DIM.  If DIM is omitted, it
     defaults to 1 (column-wise products).

     *See also:* spsum, spsumsq.

 -- Function File:  sprand (M, N, D)
 -- Function File:  sprand (S)
     Generate a random sparse matrix. The size of the matrix will be M
     by N, with a density of values given by D.  D should be between 0
     and 1. Values will be uniformly distributed between 0 and 1.

     Note: sometimes the actual density  may be a bit smaller than D.
     This is unlikely to happen for large really sparse matrices.

     If called with a single matrix argument, a random sparse matrix is
     generated wherever the matrix S is non-zero.

     *See also:* sprandn.

 -- Function File:  sprandn (M, N, D)
 -- Function File:  sprandn (S)
     Generate a random sparse matrix. The size of the matrix will be M
     by N, with a density of values given by D.  D should be between 0
     and 1. Values will be normally distributed with mean of zero and
     variance 1.

     Note: sometimes the actual density  may be a bit smaller than D.
     This is unlikely to happen for large really sparse matrices.

     If called with a single matrix argument, a random sparse matrix is
     generated wherever the matrix S is non-zero.

     *See also:* sprand.

 -- Function File:  sprandsym (N, D)
 -- Function File:  sprandsym (S)
     Generate a symmetric random sparse matrix. The size of the matrix
     will be N by N, with a density of values given by D.  D should be
     between 0 and 1. Values will be normally distributed with mean of
     zero and variance 1.

     Note: sometimes the actual density  may be a bit smaller than D.
     This is unlikely to happen for large really sparse matrices.

     If called with a single matrix argument, a random sparse matrix is
     generated wherever the matrix S is non-zero in its lower
     triangular part.

     *See also:* sprand, sprandn.

 -- Loadable Function: Y = spsum (X,DIM)
     Sum of elements along dimension DIM.  If DIM is omitted, it
     defaults to 1 (column-wise sum).

     *See also:* spprod, spsumsq.

 -- Loadable Function: Y = spsumsq (X,DIM)
     Sum of squares of elements along dimension DIM.  If DIM is
     omitted, it defaults to 1 (column-wise sum of squares).  This
     function is equivalent to computing
          spsum (x .* spconj (x), dim)
     but it uses less memory and avoids calling `spconj' if X is real.

     *See also:* spprod, spsum.

   The recommended way for the user to create a sparse matrix, is to
create two vectors containing the row and column index of the data and
a third vector of the same size containing the data to be stored. For
example

       ri = ci = d = [];
       for j = 1:c
         ri = [ri; randperm(r)(1:n)'];
         ci = [ci; j*ones(n,1)];
         d = [d; rand(n,1)];
       endfor
       s = sparse (ri, ci, d, r, c);

   creates an R-by-C sparse matrix with a random distribution of N (<R)
elements per column. The elements of the vectors do not need to be
sorted in any particular order as Octave will sort them prior to
storing the data. However, pre-sorting the data will make the creation
of the sparse matrix faster.

   The function "spconvert" takes a three or four column real matrix.
The first two columns represent the row and column index respectively
and the third and four columns, the real and imaginary parts of the
sparse matrix. The matrix can contain zero elements and the elements
can be sorted in any order. Adding zero elements is a convenient way to
define the size of the sparse matrix. For example

     s = spconvert ([1 2 3 4; 1 3 4 4; 1 2 3 0]')
     => Compressed Column Sparse (rows=4, cols=4, nnz=3)
           (1 , 1) -> 1
           (2 , 3) -> 2
           (3 , 4) -> 3

   An example of creating and filling a matrix might be

     k = 5;
     nz = r * k;
     s = spalloc (r, c, nz)
     for j = 1:c
       idx = randperm (r);
       s (:, j) = [zeros(r - k, 1); ...
             rand(k, 1)] (idx);
     endfor

   It should be noted, that due to the way that the Octave assignment
functions are written that the assignment will reallocate the memory
used by the sparse matrix at each iteration of the above loop.
Therefore the "spalloc" function ignores the NZ argument and does not
preassign the memory for the matrix. Therefore, it is vitally important
that code using to above structure should be vectorized as much as
possible to minimize the number of assignments and reduce the number of
memory allocations.

 -- Loadable Function: FM = full (SM)
     returns a full storage matrix from a sparse one

     *See also:* sparse.

 -- Function File: S = spalloc (R, C, NZ)
     Returns an empty sparse matrix of size R-by-C. As Octave resizes
     sparse matrices at the first opportunity, so that no additional
     space is needed, the argument NZ is ignored. This function is
     provided only for compatibility reasons.

     It should be noted that this means that code like

          k = 5;
          nz = r * k;
          s = spalloc (r, c, nz)
          for j = 1:c
            idx = randperm (r);
            s (:, j) = [zeros(r - k, 1); rand(k, 1)] (idx);
          endfor

     will reallocate memory at each step. It is therefore vitally
     important that code like this is vectorized as much as possible.

     *See also:* sparse, nzmax.

 -- Loadable Function: S = sparse (A)
     Create a sparse matrix from the full matrix A.  is forced back to
     a full matrix is resulting matrix is sparse

 -- Loadable Function: S = sparse (I, J, SV, M, N, NZMAX)
     Create a sparse matrix given integer index vectors I and J, a
     1-by-`nnz' vector of real of complex values SV, overall dimensions
     M and N of the sparse matrix.  The argument `nzmax' is ignored but
     accepted for compatibility with MATLAB.

     *Note*: if multiple values are specified with the same I, J
     indices, the corresponding values in S will be added.

     The following are all equivalent:

          s = sparse (i, j, s, m, n)
          s = sparse (i, j, s, m, n, "summation")
          s = sparse (i, j, s, m, n, "sum")

 -- Loadable Function: S = sparse (I, J, S, M, N, "unique")
     Same as above, except that if more than two values are specified
     for the same I, J indices, the last specified value will be used.

 -- Loadable Function: S = sparse (I, J, SV)
     Uses `M = max (I)', `N = max (J)'

 -- Loadable Function: S = sparse (M, N)
     Equivalent to `sparse ([], [], [], M, N, 0)'

     If any of SV, I or J are scalars, they are expanded to have a
     common size.

     *See also:* full.

 -- Function File: X = spconvert (M)
     This function converts for a simple sparse matrix format easily
     produced by other programs into Octave's internal sparse format.
     The input X is either a 3 or 4 column real matrix, containing the
     row, column, real and imaginary parts of the elements of the
     sparse matrix. An element with a zero real and imaginary part can
     be used to force a particular matrix size.

 -- Loadable Function:  spfind (X)
 -- Loadable Function:  spfind (X, N)
 -- Loadable Function:  spfind (X, N, DIRECTION)
 -- Loadable Function: [I, J, V spfind (...)
     A sparse version of the `find' function. Please see the `find' for
     details of its use.

     Note that this function is particularly useful for sparse
     matrices, as it extracts the non-zero elements as vectors, which
     can then be used to create the original matrix. For example,

          sz = size(a);
          [i, j, v] = spfind (a);
          b = sparse(i, j, v, sz(1), sz(2));


     *See also:* sparse.

   The above problem can be avoided in oct-files. However, the
construction of a sparse matrix from an oct-file is more complex than
can be discussed in this brief introduction, and you are referred to
chapter *Note Dynamically Linked Functions::, to have a full
description of the techniques involved.

