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

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

   Copyright (C) 1996, 1997 John W. Eaton.

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

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

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


File: octave.info,  Node: Top,  Next: Preface,  Up: (dir)

GNU Octave
**********

This manual documents how to run, install and port GNU Octave, as well
as its new features and incompatibilities, and how to report bugs.  It
corresponds to GNU Octave version 2.1.x.

* Menu:

* Preface::
* Introduction::                A brief introduction to Octave.
* Getting Started::
* Data Types::
* Numeric Data Types::
* Strings::
* Data Structures::
* Containers::
* I/O Streams::
* Variables::
* Expressions::                 Expressions.
* Evaluation::
* Statements::                  Looping and program flow control.
* Functions and Scripts::
* Error Handling::
* Debugging::
* Input and Output::
* Plotting::
* Matrix Manipulation::
* Arithmetic::
* Linear Algebra::
* Nonlinear Equations::
* Quadrature::
* Differential Equations::
* Optimization::
* Statistics::
* Financial Functions::
* Sets::
* Polynomial Manipulations::
* Control Theory::
* Signal Processing::
* Image Processing::
* Audio Processing::
* Quaternions::
* System Utilities::
* Tips::
* Trouble::                     If you have trouble installing Octave.
* Installation::                How to configure, compile and install Octave.
* Emacs::
* Grammar::
* Copying::                     The GNU General Public License.
* Concept Index::               An item for each concept.
* Variable Index::              An item for each documented variable.
* Function Index::              An item for each documented function.
* Operator Index::              An item for each documented operator.

 --- The Detailed Node Listing ---

Preface

* Acknowledgements::
* How You Can Contribute to Octave::
* Distribution::

A Brief Introduction to Octave

* Running Octave::
* Simple Examples::
* Conventions::

Conventions

* Fonts::
* Evaluation Notation::
* Printing Notation::
* Error Messages::
* Format of Descriptions::

Format of Descriptions

* A Sample Function Description::
* A Sample Command Description::
* A Sample Variable Description::

Getting Started

* Invoking Octave::
* Quitting Octave::
* Getting Help::
* Command Line Editing::
* Errors::
* Executable Octave Programs::
* Comments::

Invoking Octave

* Command Line Options::
* Startup Files::

Command Line Editing

* Cursor Motion::
* Killing and Yanking::
* Commands For Text::
* Commands For Completion::
* Commands For History::
* Customizing readline::
* Customizing the Prompt::
* Diary and Echo Commands::

Data Types

* Built-in Data Types::
* User-defined Data Types::
* Object Sizes::

Built-in Data Types

* Numeric Objects::
* String Objects::
* Data Structure Objects::

Numeric Data Types

* Matrices::
* Ranges::
* Logical Values::
* Predicates for Numeric Objects::

Matrices

* Empty Matrices::

Strings

* Creating Strings::
* Searching and Replacing::
* String Conversions::
* Character Class Functions::

Containers

* Lists::
* Cell Arrays::

Variables

* Global Variables::
* Status of Variables::
* Summary of Built-in Variables::
* Defaults from the Environment::

Expressions

* Index Expressions::
* Calling Functions::
* Arithmetic Ops::
* Comparison Ops::
* Boolean Expressions::
* Assignment Ops::
* Increment Ops::
* Operator Precedence::

Calling Functions

* Call by Value::
* Recursion::

Boolean Expressions

* Element-by-element Boolean Operators::
* Short-circuit Boolean Operators::

Statements

* The if Statement::
* The switch Statement::
* The while Statement::
* The do-until Statement::
* The for Statement::
* The break Statement::
* The continue Statement::
* The unwind_protect Statement::
* The try Statement::
* Continuation Lines::

The `for' Statement

* Looping Over Structure Elements::

Functions and Script Files

* Defining Functions::
* Multiple Return Values::
* Variable-length Argument Lists::
* Variable-length Return Lists::
* Returning From a Function::
* Function Files::
* Script Files::
* Dynamically Linked Functions::
* Organization of Functions::

Error Handling

Debugging

Input and Output

* Basic Input and Output::
* C-Style I/O Functions::

Basic Input and Output

* Terminal Output::
* Terminal Input::
* Simple File I/O::

C-Style I/O Functions

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

Plotting

* Two-Dimensional Plotting::
* Specialized Two-Dimensional Plots::
* Three-Dimensional Plotting::
* Plot Annotations::
* Multiple Plots on One Page::
* Multiple Plot Windows::
* Interaction with gnuplot::

Matrix Manipulation

* Finding Elements and Checking Conditions::
* Rearranging Matrices::
* Special Utility Matrices::
* Famous Matrices::

Arithmetic

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

Linear Algebra

* Basic Matrix Functions::
* Matrix Factorizations::
* Functions of a Matrix::

Quadrature

* Functions of One Variable::
* Orthogonal Collocation::

Differential Equations

* Ordinary Differential Equations::
* Differential-Algebraic Equations::

Optimization

* Quadratic Programming::
* Nonlinear Programming::
* Linear Least Squares::

Statistics

* Basic Statistical Functions::
* Tests::
* Models::
* Distributions::

Control Theory

* sysstruct::
* sysinterface::
* sysdisp::
* blockdiag::
* numerical::
* sysprop::
* systime::
* sysfreq::
* cacsd::
* misc::

System Data Structure

* sysstructvars::
* sysstructtf::
* sysstructzp::
* sysstructss::

System Construction and Interface Functions

* fir2sys::
* ss2sys::
* tf2sys::
* zp2sys::
* structaccess::
* structintern::

System Utilities

* Timing Utilities::
* Filesystem Utilities::
* Controlling Subprocesses::
* Process ID Information::
* Environment Variables::
* Current Working Directory::
* Password Database Functions::
* Group Database Functions::
* System Information::

Tips and Standards

* Style Tips::                  Writing clean and robust programs.
* Coding Tips::                 Making code run faster.
* Documentation Tips::          Writing readable documentation strings.
* Comment Tips::                Conventions for writing comments.
* Function Headers::            Standard headers for functions.

Known Causes of Trouble with Octave

* Actual Bugs::                 Bugs we will fix later.
* Reporting Bugs::
* Bug Criteria::
* Bug Lists::
* Bug Reporting::
* Sending Patches::
* Service::

Reporting Bugs

* Bug Criteria::
* Where: Bug Lists.             Where to send your bug report.
* Reporting: Bug Reporting.     How to report a bug effectively.
* Patches: Sending Patches.     How to send a patch for Octave.

Installing Octave

* Installation Problems::

Emacs Octave Support

* Installing EOS::
* Using Octave Mode::
* Running Octave From Within Emacs::
* Using the Emacs Info Reader for Octave::

Grammar

* Keywords::


File: octave.info,  Node: Preface,  Next: Introduction,  Prev: Top,  Up: Top

Preface
*******

Octave was originally intended to be companion software for an
undergraduate-level textbook on chemical reactor design being written by
James B. Rawlings of the University of Wisconsin-Madison and John G.
Ekerdt of the University of Texas.

   Clearly, Octave is now much more than just another `courseware'
package with limited utility beyond the classroom.  Although our
initial goals were somewhat vague, we knew that we wanted to create
something that would enable students to solve realistic problems, and
that they could use for many things other than chemical reactor design
problems.

   There are those who would say that we should be teaching the students
Fortran instead, because that is the computer language of engineering,
but every time we have tried that, the students have spent far too much
time trying to figure out why their Fortran code crashes and not enough
time learning about chemical engineering.  With Octave, most students
pick up the basics quickly, and are using it confidently in just a few
hours.

   Although it was originally intended to be used to teach reactor
design, it has been used in several other undergraduate and graduate
courses in the Chemical Engineering Department at the University of
Texas, and the math department at the University of Texas has been using
it for teaching differential equations and linear algebra as well.  If
you find it useful, please let us know.  We are always interested to
find out how Octave is being used in other places.

   Virtually everyone thinks that the name Octave has something to do
with music, but it is actually the name of a former professor of mine
who wrote a famous textbook on chemical reaction engineering, and who
was also well known for his ability to do quick `back of the envelope'
calculations.  We hope that this software will make it possible for many
people to do more ambitious computations just as easily.

   Everyone is encouraged to share this software with others under the
terms of the GNU General Public License (*note Copying::) as described
at the beginning of this manual.  You are also encouraged to help make
Octave more useful by writing and contributing additional functions for
it, and by reporting any problems you may have.

* Menu:

* Acknowledgements::
* How You Can Contribute to Octave::
* Distribution::


File: octave.info,  Node: Acknowledgements,  Next: How You Can Contribute to Octave,  Up: Preface

Acknowledgements
================

Many people have already contributed to Octave's development.  In
addition to John W. Eaton, the following people have helped write parts
of Octave or helped out in various other ways.

   * Thomas Baier <baier@ci.tuwien.ac.at> wrote the original versions
     of `popen', `pclose', `execute', `sync_system', and `async_system'.

   * David Bateman <dbateman@free.fr> improved the sort and min/max
     functions, made many functions N-d aware, converted several
     built-in functions to use Lapack instead of Linpack, split the
     functionality of `load-save.cc' out into the `octave_value'
     classes, and has contributed in many other ways.

   * Karl Berry <karl@cs.umb.edu> wrote the `kpathsea' library that
     allows Octave to recursively search directory paths for function
     and script files.

   * Georg Beyerle <gbeyerle@awi-potsdam.de> contributed code to save
     values in MATLAB's `.mat'-file format, and has provided many
     useful bug reports and suggestions.

   * John Campbell <jcc@bevo.che.wisc.edu> wrote most of the file and
     C-style input and output functions.

   * Dirk Eddelbuettel <edd@debian.org> made Octave easy to install for
     users of Debian GNU/Linux.

   * Brian Fox <bfox@gnu.org> wrote the `readline' library used for
     command history editing, and the portion of this manual that
     documents it.

   * Klaus Gebhardt <gebhardt@crunch.ikp.physik.th-darmstadt.de> ported
     Octave to OS/2.

   * Kai Habel <kai.habel@gmx.de> implemted functions for performing
     coordinate transformations.

   * A. Scottedward Hodel <A.S.Hodel@eng.auburn.edu> contributed a
     number of functions including `expm', `qzval', `qzhess', `syl',
     `lyap', and `balance'.

   * Kurt Hornik <Kurt.Hornik@ci.tuwien.ac.at> provided the `corrcoef',
     `cov', `fftconv', `fftfilt', `gcd', `lcd', `kurtosis', `null',
     `orth', `poly', `polyfit', `roots', and `skewness' functions,
     supplied documentation for these and numerous other functions,
     rewrote the Emacs mode for editing Octave code and provided its
     documentation, and has helped tremendously with testing.  He has
     also been a constant source of new ideas for improving Octave.

   * Cai Jianming <caijianming@yahoo.co.uk> contributed the inital cell
     array implementation.

   * Phil Johnson <johnsonp@nicco.sscnet.ucla.edu> has helped to make
     Linux releases available.

   * Steven G. Johnson <stevenj@alum.mit.edu> added support for ATLAS,
     saving data in HDF5 files, and ported Octave's configure script to
     Autoconf 2.50.

   * Mumit Khan <khan@nanotech.wisc.edu> helped make it possible for
     Octave to be compiled by ISO standard C++ compilers other than GCC.

   * Paul Kienzle <pkienzle@users.sf.net> has provided many
     enhancements to improve Octave's compatibility with MATLAB, and
     also maintains the collection of conributed code at
     `http://octave.sf.net'.

   * Bill Lash <lash@tellabs.com> provided the `unwrap' function.

   * Dirk Laurie <dlaurie@na-net.ornl.gov> rewrote `invhilb' to be
     faster and more accurate.

   * Friedrich Leisch <leisch@ci.tuwien.ac.at> provided the
     `mahalanobis' function.

   * Ken Neighbors <wkn@leland.stanford.edu> has provided many useful
     bug reports and comments on MATLAB compatibility.

   * Rick Niles <niles@axp745.gsfc.nasa.gov> rewrote Octave's plotting
     functions to add line styles and the ability to specify an
     unlimited number of lines in a single call.  He also continues to
     track down odd incompatibilities and bugs.

   * Mark Odegard <meo@getech.com> provided the initial implementation
     of `fread', `fwrite', `feof', and `ferror'.

   * Gabriele Pannocchia  <pannocchia@ing.unipi.it> provided the
     `dkalman.m' function, added support for singular system matrices
     to `dlqe' and `dlqr', and has made various other improvements to
     the control system functions.

   * Tony Richardson <richardson@evansville.edu> wrote Octave's image
     processing functions as well as most of the original polynomial
     functions.

   * Petter Risholm <Petter.Risholm@idi.ntnu.no> helped to implement
     much of Octave's N-d array functionality.

   * Ben Sapp <bsapp@lanl.gov> implemented the debugger functions and
     added Texinfo markup commands to the internal doc strings.

   * R. Bruce Tenison <btenison@rstc.cc.al.us> wrote the `hess' and
     `schur' functions.

   * Teresa Twaroch <twaroch@ci.tuwien.ac.at> provided the functions
     `gls' and `ols'.

   * James R. Van Zandt <jrv@vanzandt.mv.com> added support for reading
     and writing MATLAB version 5 binary data files.

   * Andreas Weingessel <Andreas.Weingessel@ci.tuwien.ac.at> wrote the
     audio functions `lin2mu', `loadaudio', `mu2lin', `playaudio',
     `record', `saveaudio', and `setaudio'.

   * Fook Fah Yap <ffy@eng.cam.ac.uk> provided the `fft' and `ifft'
     functions and valuable bug reports for early versions.

   Special thanks to the following people and organizations for
supporting the development of Octave:

   * The National Science Foundation, through grant numbers CTS-0105360,
     CTS-9708497, CTS-9311420, and CTS-8957123.

   * The industrial members of the Texas-Wisconsin Modeling and Control
     Consortium (TWMCC (http://www.che.utexas.edu/twmcc)).

   * The Paul A. Elfers Endowed Chair in Chemical Engineering at the
     University of Wisconsin-Madison.

   * Digital Equipment Corporation, for an equipment grant as part of
     their External Research Program.

   * Sun Microsystems, Inc., for an Academic Equipment grant.

   * International Business Machines, Inc., for providing equipment as
     part of a grant to the University of Texas College of Engineering.

   * Texaco Chemical Company, for providing funding to continue the
     development of this software.

   * The University of Texas College of Engineering, for providing a
     Challenge for Excellence Research Supplement, and for providing an
     Academic Development Funds grant.

   * The State of Texas, for providing funding through the Texas
     Advanced Technology Program under Grant No. 003658-078.

   * Noel Bell, Senior Engineer, Texaco Chemical Company, Austin Texas.

   * James B. Rawlings, Professor, University of Wisconsin-Madison,
     Department of Chemical Engineering.

   * Richard Stallman, for writing GNU.

   This project would not have been possible without the GNU software
used in and used to produce Octave.


File: octave.info,  Node: How You Can Contribute to Octave,  Next: Distribution,  Prev: Acknowledgements,  Up: Preface

How You Can Contribute to Octave
================================

There are a number of ways that you can contribute to help make Octave a
better system.  Perhaps the most important way to contribute is to write
high-quality code for solving new problems, and to make your code freely
available for others to use.

   If you find Octave useful, consider providing additional funding to
continue its development.  Even a modest amount of additional funding
could make a significant difference in the amount of time that is
available for development and support.

   If you cannot provide funding or contribute code, you can still help
make Octave better and more reliable by reporting any bugs you find and
by offering suggestions for ways to improve Octave.  *Note Trouble::,
for tips on how to write useful bug reports.


File: octave.info,  Node: Distribution,  Prev: How You Can Contribute to Octave,  Up: Preface

Distribution
============

Octave is "free" software.  This means that everyone is free to use it
and free to redistribute it on certain conditions.  Octave is not in
the public domain.  It is copyrighted and there are restrictions on its
distribution, but the restrictions are designed to ensure that others
will have the same freedom to use and redistribute Octave that you
have.  The precise conditions can be found in the GNU General Public
License that comes with Octave and that also appears in *Note Copying::.

   Octave is available on CD-ROM with various collections of other free
software, and from the Free Software Foundation.  Ordering a copy of
Octave from the Free Software Foundation helps to fund the development
of more free software.  For more information, write to

     Free Software Foundation
     51 Franklin Street, Fifth Floor
     Boston, MA 02110-1301-1307
     USA

   Octave is also available on the Internet from
`ftp://ftp.che.wisc.edu/pub/octave', and additional information is
available from `http://www.che.wisc.edu/octave'.


File: octave.info,  Node: Introduction,  Next: Getting Started,  Prev: Preface,  Up: Top

1 A Brief Introduction to Octave
********************************

This manual documents how to run, install and port GNU Octave, and how
to report bugs.

   GNU Octave is a high-level language, primarily intended for numerical
computations.  It provides a convenient command line interface for
solving linear and nonlinear problems numerically, and for performing
other numerical experiments.  It may also be used as a batch-oriented
language.

   GNU Octave is also freely redistributable software.  You may
redistribute it and/or modify it under the terms of the GNU General
Public License as published by the Free Software Foundation.  The GPL is
included in this manual in *Note Copying::.

   This document corresponds to Octave version 2.1.x.

* Menu:

* Running Octave::
* Simple Examples::
* Conventions::


File: octave.info,  Node: Running Octave,  Next: Simple Examples,  Up: Introduction

1.1 Running Octave
==================

On most systems, the way to invoke Octave is with the shell command
`octave'.  Octave displays an initial message and then a prompt
indicating it is ready to accept input.  You can begin typing Octave
commands immediately afterward.

   If you get into trouble, you can usually interrupt Octave by typing
`Control-C' (usually written `C-c' for short).  `C-c' gets its name
from the fact that you type it by holding down <CTRL> and then pressing
<c>.  Doing this will normally return you to Octave's prompt.

   To exit Octave, type `quit', or `exit' at the Octave prompt.

   On systems that support job control, you can suspend Octave by
sending it a `SIGTSTP' signal, usually by typing `C-z'.


File: octave.info,  Node: Simple Examples,  Next: Conventions,  Prev: Running Octave,  Up: Introduction

1.2 Simple Examples
===================

The following chapters describe all of Octave's features in detail, but
before doing that, it might be helpful to give a sampling of some of its
capabilities.

   If you are new to Octave, I recommend that you try these examples to
begin learning Octave by using it.  Lines marked with `octave:13>' are
lines you type, ending each with a carriage return.  Octave will
respond with an answer, or by displaying a graph.

Creating a Matrix
-----------------

To create a new matrix and store it in a variable so that it you can
refer to it later, type the command

     octave:1> a = [ 1, 1, 2; 3, 5, 8; 13, 21, 34 ]

Octave will respond by printing the matrix in neatly aligned columns.
Ending a command with a semicolon tells Octave to not print the result
of a command.  For example

     octave:2> b = rand (3, 2);

will create a 3 row, 2 column matrix with each element set to a random
value between zero and one.

   To display the value of any variable, simply type the name of the
variable.  For example, to display the value stored in the matrix `b',
type the command

     octave:3> b

Matrix Arithmetic
-----------------

Octave has a convenient operator notation for performing matrix
arithmetic.  For example, to multiply the matrix `a' by a scalar value,
type the command

     octave:4> 2 * a

   To multiply the two matrices `a' and `b', type the command

     octave:5> a * b

   To form the matrix product `transpose (a) * a', type the command

     octave:6> a' * a

Solving Linear Equations
------------------------

To solve the set of linear equations `aX = b', use the left division
operator, `\':

     octave:7> a \ b

This is conceptually equivalent to `inv (a) * b', but avoids computing
the inverse of a matrix directly.

   If the coefficient matrix is singular, Octave will print a warning
message and compute a minimum norm solution.

Integrating Differential Equations
----------------------------------

Octave has built-in functions for solving nonlinear differential
equations of the form

     dx
     -- = f (x, t)
     dt

with the initial condition

     x(t = t0) = x0

For Octave to integrate equations of this form, you must first provide a
definition of the function `f(x,t)'.  This is straightforward, and may
be accomplished by entering the function body directly on the command
line.  For example, the following commands define the right hand side
function for an interesting pair of nonlinear differential equations.
Note that while you are entering a function, Octave responds with a
different prompt, to indicate that it is waiting for you to complete
your input.

     octave:8> function xdot = f (x, t)
     >
     >  r = 0.25;
     >  k = 1.4;
     >  a = 1.5;
     >  b = 0.16;
     >  c = 0.9;
     >  d = 0.8;
     >
     >  xdot(1) = r*x(1)*(1 - x(1)/k) - a*x(1)*x(2)/(1 + b*x(1));
     >  xdot(2) = c*a*x(1)*x(2)/(1 + b*x(1)) - d*x(2);
     >
     > endfunction

Given the initial condition

     x0 = [1; 2];

and the set of output times as a column vector (note that the first
output time corresponds to the initial condition given above)

     t = linspace (0, 50, 200)';

it is easy to integrate the set of differential equations:

     x = lsode ("f", x0, t);

The function `lsode' uses the Livermore Solver for Ordinary
Differential Equations, described in A. C. Hindmarsh, `ODEPACK, a
Systematized Collection of ODE Solvers', in: Scientific Computing, R. S.
Stepleman et al. (Eds.), North-Holland, Amsterdam, 1983, pages 55-64.

Producing Graphical Output
--------------------------

To display the solution of the previous example graphically, use the
command

     plot (t, x)

   If you are using the X Window System, Octave will automatically
create a separate window to display the plot.  If you are using a
terminal that supports some other graphics commands, you will need to
tell Octave what kind of terminal you have.  Type the command

     gset term

to see a list of the supported terminal types.  Octave uses `gnuplot'
to display graphics, and can display graphics on any terminal that is
supported by `gnuplot'.

   To capture the output of the plot command in a file rather than
sending the output directly to your terminal, you can use a set of
commands like this

     gset term postscript
     gset output "foo.ps"
     replot

This will work for other types of output devices as well.  Octave's
`gset' command is really just piped to the `gnuplot' subprocess, so
that once you have a plot on the screen that you like, you should be
able to do something like this to create an output file suitable for
your graphics printer.

   Or, you can eliminate the intermediate file by using commands like
this

     gset term postscript
     gset output "|lpr -Pname_of_your_graphics_printer"
     replot

Editing What You Have Typed
---------------------------

At the Octave prompt, you can recall, edit, and reissue previous
commands using Emacs- or vi-style editing commands.  The default
keybindings use Emacs-style commands.  For example, to recall the
previous command, type `Control-p' (usually written `C-p' for short).
`C-p' gets its name from the fact that you type it by holding down
<CTRL> and then pressing <p>.  Doing this will normally bring back the
previous line of input.  `C-n' will bring up the next line of input,
`C-b' will move the cursor backward on the line, `C-f' will move the
cursor forward on the line, etc.

   A complete description of the command line editing capability is
given in this manual in *Note Command Line Editing::.

Help and Documentation
----------------------

Octave has an extensive help facility.  The same documentation that is
available in printed form is also available from the Octave prompt,
because both forms of the documentation are created from the same input
file.

   In order to get good help you first need to know the name of the
command that you want to use.  This name of the function may not always
be obvious, but a good place to start is to just type `help'.  This
will show you all the operators, reserved words, functions, built-in
variables, and function files.  You can then get more help on anything
that is listed by simply including the name as an argument to help.
For example,

     help plot

will display the help text for the `plot' function.

   Octave sends output that is too long to fit on one screen through a
pager like `less' or `more'.  Type a <RET> to advance one line, a <SPC>
to advance one page, and <q> to exit the pager.

   The part of Octave's help facility that allows you to read the
complete text of the printed manual from within Octave normally uses a
separate program called Info.  When you invoke Info you will be put
into a menu driven program that contains the entire Octave manual.
Help for using Info is provided in this manual in *Note Getting Help::.


File: octave.info,  Node: Conventions,  Prev: Simple Examples,  Up: Introduction

1.3 Conventions
===============

This section explains the notational conventions that are used in this
manual.  You may want to skip this section and refer back to it later.

* Menu:

* Fonts::
* Evaluation Notation::
* Printing Notation::
* Error Messages::
* Format of Descriptions::


File: octave.info,  Node: Fonts,  Next: Evaluation Notation,  Up: Conventions

1.3.1 Fonts
-----------

Examples of Octave code appear in this font or form: `svd (a)'.  Names
that represent arguments or metasyntactic variables appear in this font
or form: FIRST-NUMBER.  Commands that you type at the shell prompt
sometimes appear in this font or form: `octave --no-init-file'.
Commands that you type at the Octave prompt sometimes appear in this
font or form: `foo --bar --baz'.  Specific keys on your keyboard appear
in this font or form: <ANY>.  


File: octave.info,  Node: Evaluation Notation,  Next: Printing Notation,  Prev: Fonts,  Up: Conventions

1.3.2 Evaluation Notation
-------------------------

In the examples in this manual, results from expressions that you
evaluate are indicated with `=>'.  For example,

     sqrt (2)
          => 1.4142

You can read this as "`sqrt (2)' evaluates to 1.4142".

   In some cases, matrix values that are returned by expressions are
displayed like this

     [1, 2; 3, 4] == [1, 3; 2, 4]
          => [ 1, 0; 0, 1 ]

and in other cases, they are displayed like this

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

in order to clearly show the structure of the result.

   Sometimes to help describe one expression, another expression is
shown that produces identical results.  The exact equivalence of
expressions is indicated with `=='.  For example,

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


File: octave.info,  Node: Printing Notation,  Next: Error Messages,  Prev: Evaluation Notation,  Up: Conventions

1.3.3 Printing Notation
-----------------------

Many of the examples in this manual print text when they are evaluated.
Examples in this manual indicate printed text with `-|'.  The value
that is returned by evaluating the expression (here `1') is displayed
with `=>' and follows on a separate line.

     printf ("foo %s\n", "bar")
          -| foo bar
          => 1


File: octave.info,  Node: Error Messages,  Next: Format of Descriptions,  Prev: Printing Notation,  Up: Conventions

1.3.4 Error Messages
--------------------

Some examples signal errors.  This normally displays an error message
on your terminal.  Error messages are shown on a line starting with
`error:'.

     struct_elements ([1, 2; 3, 4])
     error: struct_elements: wrong type argument `matrix'


File: octave.info,  Node: Format of Descriptions,  Prev: Error Messages,  Up: Conventions

1.3.5 Format of Descriptions
----------------------------

Functions, commands, and variables are described in this manual in a
uniform format.  The first line of a description contains the name of
the item followed by its arguments, if any.  The category--function,
variable, or whatever--appears at the beginning of the line.  The
description follows on succeeding lines, sometimes with examples.

* Menu:

* A Sample Function Description::
* A Sample Command Description::
* A Sample Variable Description::


File: octave.info,  Node: A Sample Function Description,  Next: A Sample Command Description,  Up: Format of Descriptions

1.3.5.1 A Sample Function Description
.....................................

In a function description, the name of the function being described
appears first.  It is followed on the same line by a list of parameters.
The names used for the parameters are also used in the body of the
description.

   Here is a description of an imaginary function `foo':

 -- Function:  foo (X, Y, ...)
     The function `foo' subtracts X from Y, then adds the remaining
     arguments to the result.  If Y is not supplied, then the number 19
     is used by default.

          foo (1, [3, 5], 3, 9)
               => [ 14, 16 ]
          foo (5)
               => 14

     More generally,

          foo (W, X, Y, ...)
          ==
          X - W + Y + ...

   Any parameter whose name contains the name of a type (e.g., INTEGER,
INTEGER1 or MATRIX) is expected to be of that type.  Parameters named
OBJECT may be of any type.  Parameters with other sorts of names (e.g.,
NEW_FILE) are discussed specifically in the description of the
function.  In some sections, features common to parameters of several
functions are described at the beginning.

   Functions in Octave may be defined in several different ways.  The
catagory name for functions may include another name that indicates the
way that the function is defined.  These additional tags include

Built-in Function
     The function described is written in a language like C++, C, or
     Fortran, and is part of the compiled Octave binary.

Loadable Function
     The function described is written in a language like C++, C, or
     Fortran.  On systems that support dynamic linking of user-supplied
     functions, it may be automatically linked while Octave is running,
     but only if it is needed.  *Note Dynamically Linked Functions::.

Function File
     The function described is defined using Octave commands stored in
     a text file.  *Note Function Files::.

Mapping Function
     The function described works element-by-element for matrix and
     vector arguments.


File: octave.info,  Node: A Sample Command Description,  Next: A Sample Variable Description,  Prev: A Sample Function Description,  Up: Format of Descriptions

1.3.5.2 A Sample Command Description
....................................

Command descriptions have a format similar to function descriptions,
except that the word `Function' is replaced by `Command.  Commands are
functions that may called without surrounding their arguments in
parentheses.  For example, here is the description for Octave's `cd'
command:

 -- Command: cd dir
 -- Command: chdir dir
     Change the current working directory to DIR.  For example, `cd
     ~/octave' changes the current working directory to `~/octave'.  If
     the directory does not exist, an error message is printed and the
     working directory is not changed.


File: octave.info,  Node: A Sample Variable Description,  Prev: A Sample Command Description,  Up: Format of Descriptions

1.3.5.3 A Sample Variable Description
.....................................

A "variable" is a name that can hold a value.  Although any variable
can be set by the user, "built-in variables" typically exist
specifically so that users can change them to alter the way Octave
behaves (built-in variables are also sometimes called "user options").
Ordinary variables and built-in variables are described using a format
like that for functions except that there are no arguments.

   Here is a description of the imaginary variable
`do_what_i_mean_not_what_i_say'.

 -- Built-in Variable: do_what_i_mean_not_what_i_say
     If the value of this variable is nonzero, Octave will do what you
     actually wanted, even if you have typed a completely different and
     meaningless list of commands.

   Other variable descriptions have the same format, but `Built-in
Variable' is replaced by `Variable', for ordinary variables, or
`Constant' for symbolic constants whose values cannot be changed.


File: octave.info,  Node: Getting Started,  Next: Data Types,  Prev: Introduction,  Up: Top

2 Getting Started
*****************

This chapter explains some of Octave's basic features, including how to
start an Octave session, get help at the command prompt, edit the
command line, and write Octave programs that can be executed as commands
from your shell.

* Menu:

* Invoking Octave::
* Quitting Octave::
* Getting Help::
* Command Line Editing::
* Errors::
* Executable Octave Programs::
* Comments::


File: octave.info,  Node: Invoking Octave,  Next: Quitting Octave,  Up: Getting Started

2.1 Invoking Octave
===================

Normally, Octave is used interactively by running the program `octave'
without any arguments.  Once started, Octave reads commands from the
terminal until you tell it to exit.

   You can also specify the name of a file on the command line, and
Octave will read and execute the commands from the named file and then
exit when it is finished.

   You can further control how Octave starts by using the command-line
options described in the next section, and Octave itself can remind you
of the options available.  Type `octave --help' to display all
available options and briefly describe their use (`octave -h' is a
shorter equivalent).

* Menu:

* Command Line Options::
* Startup Files::


File: octave.info,  Node: Command Line Options,  Next: Startup Files,  Up: Invoking Octave

2.1.1 Command Line Options
--------------------------

Here is a complete list of all the command line options that Octave
accepts.

`--debug'
`-d'
     Enter parser debugging mode.  Using this option will cause Octave's
     parser to print a lot of information about the commands it reads,
     and is probably only useful if you are actually trying to debug
     the parser.

`--echo-commands'
`-x'
     Echo commands as they are executed.

`--exec-path PATH'
     Specify the path to search for programs to run.  The value of PATH
     specified on the command line will override any value of
     `OCTAVE_EXEC_PATH' found in the environment, but not any commands
     in the system or user startup files that set the built-in variable
     `EXEC_PATH'.

`--help'
`-h'
`-?'
     Print short help message and exit.

`--info-file FILENAME'
     Specify the name of the info file to use.  The value of FILENAME
     specified on the command line will override any value of
     `OCTAVE_INFO_FILE' found in the environment, but not any commands
     in the system or user startup files that set the built-in variable
     `INFO_FILE'.

`--info-program PROGRAM'
     Specify the name of the info program to use.  The value of PROGRAM
     specified on the command line will override any value of
     `OCTAVE_INFO_PROGRAM' found in the environment, but not any
     commands in the system or user startup files that set the built-in
     variable `INFO_PROGRAM'.

`--interactive'
`-i'
     Force interactive behavior.  This can be useful for running Octave
     via a remote shell command or inside an Emacs shell buffer.  For
     another way to run Octave within Emacs, see *Note Emacs::.

`--no-history'
`-H'
     Disable command-line history.

`--no-init-file'
     Don't read the `~/.octaverc' or `.octaverc' files.

`--no-line-editing'
     Disable command-line editing.

`--no-site-file'
     Don't read the site-wide `octaverc' file.

`--norc'
`-f'
     Don't read any of the system or user initialization files at
     startup.  This is equivalent to using both of the options
     `--no-init-file' and `--no-site-file'.

`--path PATH'
`-p PATH'
     Specify the path to search for function files.  The value of PATH
     specified on the command line will override any value of
     `OCTAVE_PATH' found in the environment, but not any commands in the
     system or user startup files that set the built-in variable
     `LOADPATH'.

`--silent'
`--quiet'
`-q'
     Don't print the usual greeting and version message at startup.

`--traditional'
`--braindead'
     Set initial values for user-preference variables to the following
     values for compatibility with MATLAB.

            PS1                           = ">> "
            PS2                           = ""
            beep_on_error                 = true
            crash_dumps_octave_core       = false
            default_save_format           = "mat-binary"
            fixed_point_format            = true
            page_screen_output            = false
            print_empty_dimensions        = false
            warn_function_name_clash      = false

`--verbose'
`-V'
     Turn on verbose output.

`--version'
`-v'
     Print the program version number and exit.

`FILE'
     Execute commands from FILE.

   Octave also includes several built-in variables that contain
information about the command line, including the number of arguments
and all of the options.

 -- Built-in Variable: argv
     The command line arguments passed to Octave are available in this
     variable.  For example, if you invoked Octave using the command

          octave --no-line-editing --silent

     `argv' would be a cell array of strings with the elements
     `--no-line-editing' and `--silent'.

     If you write an executable Octave script, `argv' will contain the
     list of arguments passed to the script.  *Note Executable Octave
     Programs::, for an example of how to create an executable Octave
     script.

 -- Built-in Variable: program_invocation_name
 -- Built-in Variable: program_name
     When Octave starts, the value of the built-in variable
     `program_invocation_name' is automatically set to the name that was
     typed at the shell prompt to run Octave, and the value of
     `program_name' is automatically set to the final component of
     `program_invocation_name'.  For example, if you typed
     `/usr/local/bin/octave' to start Octave, `program_invocation_name'
     would have the value `"/usr/local/bin/octave"', and `program_name'
     would have the value `"octave"'.

     If executing a script from the command line (e.g., `octave foo.m')
     or using an executable Octave script, the program name is set to
     the name of the script.  *Note Executable Octave Programs::, for
     an example of how to create an executable Octave script.

   Here is an example of using these variables to reproduce Octave's
command line.

     printf ("%s", program_name);
     for i = 1:nargin
       printf (" %s", nth (argv, i));
     endfor
     printf ("\n");

*Note Index Expressions::, for an explanation of how to properly index
arrays of strings and substrings in Octave, and *Note Defining
Functions::, for information about the variable `nargin'.


File: octave.info,  Node: Startup Files,  Prev: Command Line Options,  Up: Invoking Octave

2.1.2 Startup Files
-------------------

When Octave starts, it looks for commands to execute from the following
files:

`OCTAVE-HOME/share/octave/site/m/startup/octaverc'
     Where OCTAVE-HOME is the directory in which all of Octave is
     installed (the default is `/usr/local').  This file is provided so
     that changes to the default Octave environment can be made
     globally for all users at your site for all versions of Octave you
     have installed.  Some care should be taken when making changes to
     this file, since all users of Octave at your site will be affected.

`OCTAVE-HOME/share/octave/VERSION/m/startup/octaverc'
     Where OCTAVE-HOME is the directory in which all of Octave is
     installed (the default is `/usr/local'), and VERSION is the
     version number of Octave.  This file is provided so that changes
     to the default Octave environment can be made globally for all
     users for a particular version of Octave.  Some care should be
     taken when making changes to this file, since all users of Octave
     at your site will be affected.

`~/.octaverc'
     This file is normally used to make personal changes to the default
     Octave environment.

`.octaverc'
     This file can be used to make changes to the default Octave
     environment for a particular project.  Octave searches for this
     file in the current directory after it reads `~/.octaverc'.  Any
     use of the `cd' command in the `~/.octaverc' file will affect the
     directory that Octave searches for the file `.octaverc'.

     If you start Octave in your home directory, commands from from the
     file `~/.octaverc' will only be executed once.

   A message will be displayed as each of the startup files is read if
you invoke Octave with the `--verbose' option but without the
`--silent' option.

   Startup files may contain any valid Octave commands, including
function definitions.


File: octave.info,  Node: Quitting Octave,  Next: Getting Help,  Prev: Invoking Octave,  Up: Getting Started

2.2 Quitting Octave
===================

 -- Built-in Function:  exit (STATUS)
 -- Built-in Function:  quit (STATUS)
     Exit the current Octave session.  If the optional integer value
     STATUS is supplied, pass that value to the operating system as the
     Octave's exit status.

 -- Built-in Function:  atexit (FCN)
     Register a function to be called when Octave exits.  For example,

          function print_fortune ()
            printf ("\n%s\n", system ("fortune"));
            fflush (stdout);
          endfunction
          atexit ("print_fortune");

     will print a message when Octave exits.


File: octave.info,  Node: Getting Help,  Next: Command Line Editing,  Prev: Quitting Octave,  Up: Getting Started

2.3 Commands for Getting Help
=============================

The entire text of this manual is available from the Octave prompt via
the command `help -i'.  In addition, the documentation for individual
user-written functions and variables is also available via the `help'
command.  This section describes the commands used for reading the
manual and the documentation strings for user-supplied functions and
variables.  *Note Function Files::, for more information about how to
document the functions you write.

 -- Command: help
     Octave's `help' command can be used to print brief usage-style
     messages, or to display information directly from an on-line
     version of the printed manual, using the GNU Info browser.  If
     invoked without any arguments, `help' prints a list of all the
     available operators, functions, and built-in variables.  If the
     first argument is `-i', the `help' command searches the index of
     the on-line version of this manual for the given topics.

     For example, the command `help help' prints a short message
     describing the `help' command, and `help -i help' starts the GNU
     Info browser at this node in the on-line version of the manual.

     Once the GNU Info browser is running, help for using it is
     available using the command `C-h'.

   The help command can give you information about operators, but not
the comma and semicolons that are used as command separators.  To get
help for those, you must type `help comma' or `help semicolon'.

 -- Built-in Variable: INFO_FILE
     The variable `INFO_FILE' names the location of the Octave info
     file.  The default value is `"OCTAVE-HOME/info/octave.info"', in
     which OCTAVE-HOME is the directory where all of Octave is
     installed.

 -- Built-in Variable: INFO_PROGRAM
     The variable `INFO_PROGRAM' names the info program to run.  Its
     default initial value is
     `"OCTAVE-HOME/libexec/octave/VERSION/exec/ARCH/info"' in which
     OCTAVE-HOME is the directory where all of Octave is installed,
     VERSION is the Octave version number, and ARCH is the system type
     (for example, `i686-pc-linux-gnu').  The default initial value may
     be overridden by the environment variable `OCTAVE_INFO_PROGRAM',
     or the command line argument `--info-program NAME', or by setting
     the value of `INFO_PROGRAM' in a startup script

 -- Built-in Variable: MAKEINFO_PROGRAM
     The variable `MAKEINFO_PROGRAM' names the makeinfo program that
     Octave runs to format help text that contains Texinfo markup
     commands.  Its default initial value is `"makeinfo"'.

 -- Built-in Variable: suppress_verbose_help_message
     If the value of `suppress_verbose_help_message' is nonzero, Octave
     will not add additional help information to the end of the output
     from the `help' command and usage messages for built-in commands.


File: octave.info,  Node: Command Line Editing,  Next: Errors,  Prev: Getting Help,  Up: Getting Started

2.4 Command Line Editing
========================

Octave uses the GNU readline library to provide an extensive set of
command-line editing and history features.  Only the most common
features are described in this manual.  Please see The GNU Readline
Library manual for more information.

   To insert printing characters (letters, digits, symbols, etc.),
simply type the character.  Octave will insert the character at the
cursor and advance the cursor forward.

   Many of the command-line editing functions operate using control
characters.  For example, the character `Control-a' moves the cursor to
the beginning of the line.  To type `C-a', hold down <CTRL> and then
press <a>.  In the following sections, control characters such as
`Control-a' are written as `C-a'.

   Another set of command-line editing functions use Meta characters.
On some terminals, you type `M-u' by holding down <META> and pressing
<u>.  If your terminal does not have a <META> key, you can still type
Meta charcters using two-character sequences starting with `ESC'.
Thus, to enter `M-u', you could type <ESC><u>.  The `ESC' character
sequences are also allowed on terminals with real Meta keys.  In the
following sections, Meta characters such as `Meta-u' are written as
`M-u'.

* Menu:

* Cursor Motion::
* Killing and Yanking::
* Commands For Text::
* Commands For Completion::
* Commands For History::
* Customizing readline::
* Customizing the Prompt::
* Diary and Echo Commands::


File: octave.info,  Node: Cursor Motion,  Next: Killing and Yanking,  Up: Command Line Editing

2.4.1 Cursor Motion
-------------------

The following commands allow you to position the cursor.

`C-b'
     Move back one character.

`C-f'
     Move forward one character.

`<DEL>'
     Delete the character to the left of the cursor.

`C-d'
     Delete the character underneath the cursor.

`M-f'
     Move forward a word.

`M-b'
     Move backward a word.

`C-a'
     Move to the start of the line.

`C-e'
     Move to the end of the line.

`C-l'
     Clear the screen, reprinting the current line at the top.

`C-_'
`C-/'
     Undo the last thing that you did.  You can undo all the way back
     to an empty line.

`M-r'
     Undo all changes made to this line.  This is like typing the `undo'
     command enough times to get back to the beginning.

   The above table describes the most basic possible keystrokes that
you need in order to do editing of the input line.  On most terminals,
you can also use the arrow keys in place of `C-f' and `C-b' to move
forward and backward.

   Notice how `C-f' moves forward a character, while `M-f' moves
forward a word.  It is a loose convention that control keystrokes
operate on characters while meta keystrokes operate on words.

   There is also a function available so that you can clear the screen
from within Octave programs.

 -- Built-in Function:  clc ()
 -- Built-in Function:  home ()
     Clear the terminal screen and move the cursor to the upper left
     corner.


File: octave.info,  Node: Killing and Yanking,  Next: Commands For Text,  Prev: Cursor Motion,  Up: Command Line Editing

2.4.2 Killing and Yanking
-------------------------

"Killing" text means to delete the text from the line, but to save it
away for later use, usually by "yanking" it back into the line.  If the
description for a command says that it `kills' text, then you can be
sure that you can get the text back in a different (or the same) place
later.

   Here is the list of commands for killing text.

`C-k'
     Kill the text from the current cursor position to the end of the
     line.

`M-d'
     Kill from the cursor to the end of the current word, or if between
     words, to the end of the next word.

`M-<DEL>'
     Kill from the cursor to the start of the previous word, or if
     between words, to the start of the previous word.

`C-w'
     Kill from the cursor to the previous whitespace.  This is
     different than `M-<DEL>' because the word boundaries differ.

   And, here is how to "yank" the text back into the line.  Yanking
means to copy the most-recently-killed text from the kill buffer.

`C-y'
     Yank the most recently killed text back into the buffer at the
     cursor.

`M-y'
     Rotate the kill-ring, and yank the new top.  You can only do this
     if the prior command is `C-y' or `M-y'.

   When you use a kill command, the text is saved in a "kill-ring".
Any number of consecutive kills save all of the killed text together, so
that when you yank it back, you get it in one clean sweep.  The kill
ring is not line specific; the text that you killed on a previously
typed line is available to be yanked back later, when you are typing
another line.


File: octave.info,  Node: Commands For Text,  Next: Commands For Completion,  Prev: Killing and Yanking,  Up: Command Line Editing

2.4.3 Commands For Changing Text
--------------------------------

The following commands can be used for entering characters that would
otherwise have a special meaning (e.g., `TAB', `C-q', etc.), or for
quickly correcting typing mistakes.

`C-q'
`C-v'
     Add the next character that you type to the line verbatim.  This is
     how to insert things like `C-q' for example.

`M-<TAB>'
     Insert a tab character.

`C-t'
     Drag the character before the cursor forward over the character at
     the cursor, also moving the cursor forward.  If the cursor is at
     the end of the line, then transpose the two characters before it.

`M-t'
     Drag the word behind the cursor past the word in front of the
     cursor moving the cursor over that word as well.

`M-u'
     Uppercase the characters following the cursor to the end of the
     current (or following) word, moving the cursor to the end of the
     word.

`M-l'
     Lowecase the characters following the cursor to the end of the
     current (or following) word, moving the cursor to the end of the
     word.

`M-c'
     Uppercase the character following the cursor (or the beginning of
     the next word if the cursor is between words), moving the cursor
     to the end of the word.


File: octave.info,  Node: Commands For Completion,  Next: Commands For History,  Prev: Commands For Text,  Up: Command Line Editing

2.4.4 Letting Readline Type For You
-----------------------------------

The following commands allow Octave to complete command and variable
names for you.

`<TAB>'
     Attempt to do completion on the text before the cursor.  Octave can
     complete the names of commands and variables.

`M-?'
     List the possible completions of the text before the cursor.

 -- Built-in Variable: completion_append_char
     The value of `completion_append_char' is used as the character to
     append to successful command-line completion attempts.  The default
     value is `" "' (a single space).

 -- Built-in Function:  completion_matches (HINT)
     Generate possible completions given HINT.

     This function is provided for the benefit of programs like Emacs
     which might be controlling Octave and handling user input.  The
     current command number is not incremented when this function is
     called.  This is a feature, not a bug.


File: octave.info,  Node: Commands For History,  Next: Customizing readline,  Prev: Commands For Completion,  Up: Command Line Editing

2.4.5 Commands For Manipulating The History
-------------------------------------------

Octave normally keeps track of the commands you type so that you can
recall previous commands to edit or execute them again.  When you exit
Octave, the most recent commands you have typed, up to the number
specified by the variable `history_size', are saved in a file.  When
Octave starts, it loads an initial list of commands from the file named
by the variable `history_file'.

   Here are the commands for simple browsing and searching the history
list.

`<LFD>'
`<RET>'
     Accept the line regardless of where the cursor is.  If this line is
     non-empty, add it to the history list.  If this line was a history
     line, then restore the history line to its original state.

`C-p'
     Move `up' through the history list.

`C-n'
     Move `down' through the history list.

`M-<'
     Move to the first line in the history.

`M->'
     Move to the end of the input history, i.e., the line you are
     entering!

`C-r'
     Search backward starting at the current line and moving `up'
     through the history as necessary.  This is an incremental search.

`C-s'
     Search forward starting at the current line and moving `down'
     through the history as necessary.

   On most terminals, you can also use the arrow keys in place of `C-p'
and `C-n' to move through the history list.

   In addition to the keyboard commands for moving through the history
list, Octave provides three functions for viewing, editing, and
re-running chunks of commands from the history list.

 -- Command: history options
     If invoked with no arguments, `history' displays a list of commands
     that you have executed.  Valid options are:

    `-w FILE'
          Write the current history to the file FILE.  If the name is
          omitted, use the default history file (normally
          `~/.octave_hist').

    `-r FILE'
          Read the file FILE, replacing the current history list with
          its contents.  If the name is omitted, use the default
          history file (normally `~/.octave_hist').

    `N'
          Only display the most recent N lines of history.

    `-q'
          Don't number the displayed lines of history.  This is useful
          for cutting and pasting commands if you are using the X
          Window System.

     For example, to display the five most recent commands that you have
     typed without displaying line numbers, use the command `history -q
     5'.

 -- Command: edit_history options
     If invoked with no arguments, `edit_history' allows you to edit the
     history list using the editor named by the variable `EDITOR'.  The
     commands to be edited are first copied to a temporary file.  When
     you exit the editor, Octave executes the commands that remain in
     the file.  It is often more convenient to use `edit_history' to
     define functions rather than attempting to enter them directly on
     the command line.  By default, the block of commands is executed
     as soon as you exit the editor.  To avoid executing any commands,
     simply delete all the lines from the buffer before exiting the
     editor.

     The `edit_history' command takes two optional arguments specifying
     the history numbers of first and last commands to edit.  For
     example, the command

          edit_history 13

     extracts all the commands from the 13th through the last in the
     history list.  The command

          edit_history 13 169

     only extracts commands 13 through 169.  Specifying a larger number
     for the first command than the last command reverses the list of
     commands before placing them in the buffer to be edited.  If both
     arguments are omitted, the previous command in the history list is
     used.

 -- Command: run_history [first] [last]
     Similar to `edit_history', except that the editor is not invoked,
     and the commands are simply executed as they appear in the history
     list.

 -- Built-in Variable: EDITOR
     A string naming the editor to use with the `edit_history' command.
     If the environment variable `EDITOR' is set when Octave starts, its
     value is used as the default.  Otherwise, `EDITOR' is set to
     `"emacs"'.

 -- Built-in Variable: history_file
     This variable specifies the name of the file used to store command
     history.  The default value is `"~/.octave_hist"', but may be
     overridden by the environment variable `OCTAVE_HISTFILE'.

 -- Built-in Variable: history_size
     This variable specifies how many entries to store in the history
     file.  The default value is `1024', but may be overridden by the
     environment variable `OCTAVE_HISTSIZE'.

 -- Built-in Variable: saving_history
     If the value of `saving_history' is nonzero, command entered on
     the command line are saved in the file specified by the variable
     `history_file'.


File: octave.info,  Node: Customizing readline,  Next: Customizing the Prompt,  Prev: Commands For History,  Up: Command Line Editing

2.4.6 Customizing `readline'
----------------------------

 -- Built-in Function:  read_readline_init_file (FILE)
     Read the readline library initialiazation file FILE.  If FILE is
     omitted, read the default initialization file (normally
     `~/.inputrc'.


File: octave.info,  Node: Customizing the Prompt,  Next: Diary and Echo Commands,  Prev: Customizing readline,  Up: Command Line Editing

2.4.7 Customizing the Prompt
----------------------------

The following variables are available for customizing the appearance of
the command-line prompts.  Octave allows the prompt to be customized by
inserting a number of backslash-escaped special characters that are
decoded as follows:

`\t'
     The time.

`\d'
     The date.

`\n'
     Begins a new line by printing the equivalent of a carriage return
     followed by a line feed.

`\s'
     The name of the program (usually just `octave').

`\w'
     The current working directory.

`\W'
     The basename of the current working directory.

`\u'
     The username of the current user.

`\h'
     The hostname, up to the first `.'.

`\H'
     The hostname.

`\#'
     The command number of this command, counting from when Octave
     starts.

`\!'
     The history number of this command.  This differs from `\#' by the
     number of commands in the history list when Octave starts.

`\$'
     If the effective UID is 0, a `#', otherwise a `$'.

`\nnn'
     The character whose character code in octal is NNN.

`\\'
     A backslash.

 -- Built-in Variable: PS1
     The primary prompt string.  When executing interactively, Octave
     displays the primary prompt `PS1' when it is ready to read a
     command.

     The default value of `PS1' is `"\s:\#> "'.  To change it, use a
     command like

          octave:13> PS1 = "\\u@\\H> "

     which will result in the prompt `boris@kremvax> ' for the user
     `boris' logged in on the host `kremvax.kgb.su'.  Note that two
     backslashes are required to enter a backslash into a string.
     *Note Strings::.

 -- Built-in Variable: PS2
     The secondary prompt string, which is printed when Octave is
     expecting additional input to complete a command.  For example,
     when defining a function over several lines, Octave will print the
     value of `PS1' at the beginning of each line after the first.  The
     default value of `PS2' is `"> "'.

 -- Built-in Variable: PS4
     If Octave is invoked with the `--echo-commands' option, the value
     of `PS4' is printed before each line of input that is echoed.  The
     default value of `PS4' is `"+ "'.  *Note Invoking Octave::, for a
     description of `--echo-commands'.


File: octave.info,  Node: Diary and Echo Commands,  Prev: Customizing the Prompt,  Up: Command Line Editing

2.4.8 Diary and Echo Commands
-----------------------------

Octave's diary feature allows you to keep a log of all or part of an
interactive session by recording the input you type and the output that
Octave produces in a separate file.

 -- Command: diary options
     Create a list of all commands _and_ the output they produce, mixed
     together just as you see them on your terminal.  Valid options are:

    `on'
          Start recording your session in a file called `diary' in your
          current working directory.

    `off'
          Stop recording your session in the diary file.

    `FILE'
          Record your session in the file named FILE.

     Without any arguments, `diary' toggles the current diary state.

   Sometimes it is useful to see the commands in a function or script as
they are being evaluated.  This can be especially helpful for debugging
some kinds of problems.

 -- Command: echo options
     Control whether commands are displayed as they are executed.  Valid
     options are:

    `on'
          Enable echoing of commands as they are executed in script
          files.

    `off'
          Disable echoing of commands as they are executed in script
          files.

    `on all'
          Enable echoing of commands as they are executed in script
          files and functions.

    `off all'
          Disable echoing of commands as they are executed in script
          files and functions.

     If invoked without any arguments, `echo' toggles the current echo
     state.

 -- Built-in Variable: echo_executing_commands
     This variable may also be used to control the echo state.  It may
     be the sum of the following values:

    1
          Echo commands read from script files.

    2
          Echo commands from functions.

    4
          Echo commands read from command line.

     More than one state can be active at once.  For example, a value
     of 3 is equivalent to the command `echo on all'.

     The value of `echo_executing_commands' is set by the `echo'
     command and the command line option `--echo-input'.


File: octave.info,  Node: Errors,  Next: Executable Octave Programs,  Prev: Command Line Editing,  Up: Getting Started

2.5 How Octave Reports Errors
=============================

Octave reports two kinds of errors for invalid programs.

   A "parse error" occurs if Octave cannot understand something you
have typed.  For example, if you misspell a keyword,

     octave:13> functon y = f (x) y = x^2; endfunction

Octave will respond immediately with a message like this:

     parse error:

       functon y = f (x) y = x^2; endfunction
               ^

For most parse errors, Octave uses a caret (`^') to mark the point on
the line where it was unable to make sense of your input.  In this
case, Octave generated an error message because the keyword `function'
was misspelled.  Instead of seeing `function f', Octave saw two
consecutive variable names, which is invalid in this context.  It
marked the error at `y' because the first name by itself was accepted
as valid input.

   Another class of error message occurs at evaluation time.  These
errors are called "run-time errors", or sometimes "evaluation errors"
because they occur when your program is being "run", or "evaluated".
For example, if after correcting the mistake in the previous function
definition, you type

     octave:13> f ()

Octave will respond with

     error: `x' undefined near line 1 column 24
     error: evaluating expression near line 1, column 24
     error: evaluating assignment expression near line 1, column 22
     error: called from `f'

   This error message has several parts, and gives you quite a bit of
information to help you locate the source of the error.  The messages
are generated from the point of the innermost error, and provide a
traceback of enclosing expressions and function calls.

   In the example above, the first line indicates that a variable named
`x' was found to be undefined near line 1 and column 24 of some
function or expression.  For errors occurring within functions, lines
are counted from the beginning of the file containing the function
definition.  For errors occurring at the top level, the line number
indicates the input line number, which is usually displayed in the
prompt string.

   The second and third lines in the example indicate that the error
occurred within an assignment expression, and the last line of the error
message indicates that the error occurred within the function `f'.  If
the function `f' had been called from another function, for example,
`g', the list of errors would have ended with one more line:

     error: called from `g'

   These lists of function calls usually make it fairly easy to trace
the path your program took before the error occurred, and to correct the
error before trying again.


File: octave.info,  Node: Executable Octave Programs,  Next: Comments,  Prev: Errors,  Up: Getting Started

2.6 Executable Octave Programs
==============================

Once you have learned Octave, you may want to write self-contained
Octave scripts, using the `#!' script mechanism.  You can do this on
GNU systems and on many Unix systems (1)

   For example, you could create a text file named `hello', containing
the following lines:

     #! OCTAVE-INTERPRETER-NAME -qf
     # a sample Octave program
     printf ("Hello, world!\n");

(where OCTAVE-INTERPRETER-NAME should be replaced with the full file
name for your Octave binary).  After making this file executable (with
the `chmod' command), you can simply type:

     hello

at the shell, and the system will arrange to run Octave as if you had
typed:

     octave hello

   The line beginning with `#!' lists the full file name of an
interpreter to be run, and an optional initial command line argument to
pass to that interpreter.  The operating system then runs the
interpreter with the given argument and the full argument list of the
executed program.  The first argument in the list is the full file name
of the Octave program. The rest of the argument list will either be
options to Octave, or data files, or both.  The `-qf' option is usually
specified in stand-alone Octave programs to prevent them from printing
the normal startup message, and to keep them from behaving differently
depending on the contents of a particular user's `~/.octaverc' file.
*Note Invoking Octave::.  Note that some operating systems may place a
limit on the number of characters that are recognized after `#!'.

   Self-contained Octave scripts are useful when you want to write a
program which users can invoke without knowing that the program is
written in the Octave language.

   If you invoke an executable Octave script with command line
arguments, the arguments are available in the built-in variable `argv'.
*Note Command Line Options::.  For example, the following program will
reproduce the command line that is used to execute it.

     #! /bin/octave -qf
     printf ("%s", program_name);
     for i = 1:nargin
       printf (" %s", argv{i});
     endfor
     printf ("\n");

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

   (1) The `#!' mechanism works on Unix systems derived from Berkeley
Unix, System V Release 4, and some System V Release 3 systems.


File: octave.info,  Node: Comments,  Prev: Executable Octave Programs,  Up: Getting Started

2.7 Comments in Octave Programs
===============================

A "comment" is some text that is included in a program for the sake of
human readers, and that is not really part of the program.  Comments
can explain what the program does, and how it works.  Nearly all
programming languages have provisions for comments, because programs are
typically hard to understand without them.

   In the Octave language, a comment starts with either the sharp sign
character, `#', or the percent symbol `%' and continues to the end of
the line.  The Octave interpreter ignores the rest of a line following
a sharp sign or percent symbol.  For example, we could have put the
following into the function `f':

     function xdot = f (x, t)

     # usage: f (x, t)
     #
     # This function defines the right hand
     # side functions for a set of nonlinear
     # differential equations.

       r = 0.25;
       ...
     endfunction

   The `help' command (*note Getting Help::) is able to find the first
block of comments in a function (even those that are composed directly
on the command line).  This means that users of Octave can use the same
commands to get help for built-in functions, and for functions that you
have defined.  For example, after defining the function `f' above, the
command `help f' produces the output

      usage: f (x, t)

      This function defines the right hand
      side functions for a set of nonlinear
      differential equations.

   Although it is possible to put comment lines into keyboard-composed
throw-away Octave programs, it usually isn't very useful, because the
purpose of a comment is to help you or another person understand the
program at a later time.


File: octave.info,  Node: Data Types,  Next: Numeric Data Types,  Prev: Getting Started,  Up: Top

3 Data Types
************

All versions of Octave include a number of built-in data types,
including real and complex scalars and matrices, character strings, and
a data structure type.

   It is also possible to define new specialized data types by writing a
small amount of C++ code.  On some systems, new data types can be loaded
dynamically while Octave is running, so it is not necessary to recompile
all of Octave just to add a new type.  *Note Dynamically Linked
Functions::, for more information about Octave's dynamic linking
capabilities.  *Note User-defined Data Types:: describes what you must
do to define a new data type for Octave.

 -- Built-in Function:  typeinfo (EXPR)
     Return the type of the expression EXPR, as a string.  If EXPR  is
     omitted, return an array of strings containing all the currently
     installed data types.

* Menu:

* Built-in Data Types::
* User-defined Data Types::
* Object Sizes::


File: octave.info,  Node: Built-in Data Types,  Next: User-defined Data Types,  Up: Data Types

3.1 Built-in Data Types
=======================

The standard built-in data types are real and complex scalars and
matrices, ranges, character strings, and a data structure type.
Additional built-in data types may be added in future versions.  If you
need a specialized data type that is not currently provided as a
built-in type, you are encouraged to write your own user-defined data
type and contribute it for distribution in a future release of Octave.

* Menu:

* Numeric Objects::
* Missing Data::
* String Objects::
* Data Structure Objects::


File: octave.info,  Node: Numeric Objects,  Next: Missing Data,  Up: Built-in Data Types

3.1.1 Numeric Objects
---------------------

Octave's built-in numeric objects include real and complex scalars and
matrices.  All built-in numeric data is currently stored as double
precision numbers.  On systems that use the IEEE floating point format,
values in the range of approximately  2.2251e-308 to 1.7977e+308  can
be stored, and the relative precision is approximately  2.2204e-16.
The exact values are given by the variables `realmin', `realmax', and
`eps', respectively.

   Matrix objects can be of any size, and can be dynamically reshaped
and resized.  It is easy to extract individual rows, columns, or
submatrices using a variety of powerful indexing features.  *Note Index
Expressions::.

   *Note Numeric Data Types::, for more information.


File: octave.info,  Node: Missing Data,  Next: String Objects,  Prev: Numeric Objects,  Up: Built-in Data Types

3.1.2 Missing Data
------------------

 -- Built-in Variable: NA
     Missing value.

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

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

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

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


File: octave.info,  Node: String Objects,  Next: Data Structure Objects,  Prev: Missing Data,  Up: Built-in Data Types

3.1.3 String Objects
--------------------

A character string in Octave consists of a sequence of characters
enclosed in either double-quote or single-quote marks.  Internally,
Octave currently stores strings as matrices of characters.  All the
indexing operations that work for matrix objects also work for strings.

   *Note Strings::, for more information.


File: octave.info,  Node: Data Structure Objects,  Prev: String Objects,  Up: Built-in Data Types

3.1.4 Data Structure Objects
----------------------------

Octave's data structure type can help you to organize related objects of
different types.  The current implementation uses an associative array
with indices limited to strings, but the syntax is more like C-style
structures.

   *Note Data Structures::, for more information.


File: octave.info,  Node: User-defined Data Types,  Next: Object Sizes,  Prev: Built-in Data Types,  Up: Data Types

3.2 User-defined Data Types
===========================

Someday I hope to expand this to include a complete description of
Octave's mechanism for managing user-defined data types.  Until this
feature is documented here, you will have to make do by reading the code
in the `ov.h', `ops.h', and related files from Octave's `src' directory.


File: octave.info,  Node: Object Sizes,  Prev: User-defined Data Types,  Up: Data Types

3.3 Object Sizes
================

The following functions allow you to determine the size of a variable or
expression.  These functions are defined for all objects.  They return
-1 when the operation doesn't make sense.  For example, Octave's data
structure type doesn't have rows or columns, so the `rows' and
`columns' functions return -1 for structure arguments.

 -- Function File:  columns (A)
     Return the number of columns of A.

 -- Function File:  rows (A)
     Return the number of rows of A.

 -- Built-in Function:  length (A)
     Return the `length' of the object A.  For matrix objects, the
     length is the number of rows or columns, whichever is greater (this
     odd definition is used for compatibility with Matlab).

 -- Built-in Function:  size (A, N)
     Return the number rows and columns of A.

     With one input argument and one output argument, the result is
     returned in a row vector.  If there are multiple output arguments,
     the number of rows is assigned to the first, and the number of
     columns to the second, etc.  For example,

          size ([1, 2; 3, 4; 5, 6])
               => [ 3, 2 ]

          [nr, nc] = size ([1, 2; 3, 4; 5, 6])
               => nr = 3
               => nc = 2

     If given a second argument, `size' will return the size of the
     corresponding dimension.  For example

          size ([1, 2; 3, 4; 5, 6], 2)
               => 2

     returns the number of columns in the given matrix.

 -- Built-in Function:  isempty (A)
     Return 1 if A is an empty matrix (either the number of rows, or
     the number of columns, or both are zero).  Otherwise, return 0.


File: octave.info,  Node: Numeric Data Types,  Next: Strings,  Prev: Data Types,  Up: Top

4 Numeric Data Types
********************

A "numeric constant" may be a scalar, a vector, or a matrix, and it may
contain complex values.

   The simplest form of a numeric constant, a scalar, is a single number
that can be an integer, a decimal fraction, a number in scientific
(exponential) notation, or a complex number.  Note that all numeric
constants are represented within Octave in double-precision floating
point format (complex constants are stored as pairs of double-precision
floating point values).  Here are some examples of real-valued numeric
constants, which all have the same value:

     105
     1.05e+2
     1050e-1

   To specify complex constants, you can write an expression of the form

     3 + 4i
     3.0 + 4.0i
     0.3e1 + 40e-1i

   all of which are equivalent.  The letter `i' in the previous example
stands for the pure imaginary constant, defined as   `sqrt (-1)'.

   For Octave to recognize a value as the imaginary part of a complex
constant, a space must not appear between the number and the `i'.  If
it does, Octave will print an error message, like this:

     octave:13> 3 + 4 i

     parse error:

       3 + 4 i
             ^

   You may also use `j', `I', or `J' in place of the `i' above.  All
four forms are equivalent.

* Menu:

* Matrices::
* Ranges::
* Logical Values::
* Predicates for Numeric Objects::


File: octave.info,  Node: Matrices,  Next: Ranges,  Up: Numeric Data Types

4.1 Matrices
============

It is easy to define a matrix of values in Octave.  The size of the
matrix is determined automatically, so it is not necessary to explicitly
state the dimensions.  The expression

     a = [1, 2; 3, 4]

results in the matrix


             /      \
             | 1  2 |
       a  =  |      |
             | 3  4 |
             \      /

   Elements of a matrix may be arbitrary expressions, provided that the
dimensions all make sense when combining the various pieces.  For
example, given the above matrix, the expression

     [ a, a ]

produces the matrix

     ans =

       1  2  1  2
       3  4  3  4

but the expression

     [ a, 1 ]

produces the error

     error: number of rows must match near line 13, column 6

(assuming that this expression was entered as the first thing on line
13, of course).

   Inside the square brackets that delimit a matrix expression, Octave
looks at the surrounding context to determine whether spaces and newline
characters should be converted into element and row separators, or
simply ignored, so an expression like

     a = [ 1 2
           3 4 ]

will work.  However, some possible sources of confusion remain.  For
example, in the expression

     [ 1 - 1 ]

the `-' is treated as a binary operator and the result is the scalar 0,
but in the expression

     [ 1 -1 ]

the `-' is treated as a unary operator and the result is the vector `[
1, -1 ]'.  Similarly, the expression

     [ sin (pi) ]

will be parsed as

     [ sin, (pi) ]

and will result in an error since the `sin' function will be called
with no arguments.  To get around this, you must omit the space between
`sin' and the opening parenthesis, or enclose the expression in a set
of parentheses:

     [ (sin (pi)) ]

   Whitespace surrounding the single quote character (`'', used as a
transpose operator and for delimiting character strings) can also cause
confusion.  Given `a = 1', the expression

     [ 1 a' ]

results in the single quote character being treated as a transpose
operator and the result is the vector `[ 1, 1 ]', but the expression

     [ 1 a ' ]

produces the error message

     error: unterminated string constant

because to not do so would cause trouble when parsing the valid
expression

     [ a 'foo' ]

   For clarity, it is probably best to always use commas and semicolons
to separate matrix elements and rows.

 -- Built-in Variable: warn_separator_insert
     Print warning if commas or semicolons might be inserted
     automatically in literal matrices.

   When you type a matrix or the name of a variable whose value is a
matrix, Octave responds by printing the matrix in with neatly aligned
rows and columns.  If the rows of the matrix are too large to fit on the
screen, Octave splits the matrix and displays a header before each
section to indicate which columns are being displayed.  You can use the
following variables to control the format of the output.

 -- Built-in Variable: output_max_field_width
     This variable specifies the maximum width of a numeric output
     field.  The default value is 10.

 -- Built-in Variable: output_precision
     This variable specifies the minimum number of significant figures
     to display for numeric output.  The default value is 5.

   It is possible to achieve a wide range of output styles by using
different values of `output_precision' and `output_max_field_width'.
Reasonable combinations can be set using the `format' function.  *Note
Basic Input and Output::.

 -- Built-in Variable: split_long_rows
     For large matrices, Octave may not be able to display all the
     columns of a given row on one line of your screen.  This can
     result in missing information or output that is nearly impossible
     to decipher, depending on whether your terminal truncates or wraps
     long lines.

     If the value of `split_long_rows' is nonzero, Octave will display
     the matrix in a series of smaller pieces, each of which can fit
     within the limits of your terminal width.  Each set of rows is
     labeled so that you can easily see which columns are currently
     being displayed.  For example:

          octave:13> rand (2,10)
          ans =

           Columns 1 through 6:

            0.75883  0.93290  0.40064  0.43818  0.94958  0.16467
            0.75697  0.51942  0.40031  0.61784  0.92309  0.40201

           Columns 7 through 10:

            0.90174  0.11854  0.72313  0.73326
            0.44672  0.94303  0.56564  0.82150

     The default value of `split_long_rows' is nonzero.

   Octave automatically switches to scientific notation when values
become very large or very small.  This guarantees that you will see
several significant figures for every value in a matrix.  If you would
prefer to see all values in a matrix printed in a fixed point format,
you can set the built-in variable `fixed_point_format' to a nonzero
value.  But doing so is not recommended, because it can produce output
that can easily be misinterpreted.

 -- Built-in Variable: fixed_point_format
     If the value of this variable is nonzero, Octave will scale all
     values in a matrix so that the largest may be written with one
     leading digit.  The scaling factor is printed on the first line of
     output.  For example,

          octave:1> logspace (1, 7, 5)'
          ans =

            1.0e+07  *

            0.00000
            0.00003
            0.00100
            0.03162
            1.00000

     Notice that first value appears to be zero when it is actually 1.
     For this reason, you should be careful when setting
     `fixed_point_format' to a nonzero value.

     The default value of `fixed_point_format' is 0.

* Menu:

* Empty Matrices::


File: octave.info,  Node: Empty Matrices,  Up: Matrices

4.1.1 Empty Matrices
--------------------

A matrix may have one or both dimensions zero, and operations on empty
matrices are handled as described by Carl de Boor in `An Empty
Exercise', SIGNUM, Volume 25, pages 2-6, 1990 and C. N. Nett and W. M.
Haddad, in `A System-Theoretic Appropriate Realization of the Empty
Matrix Concept', IEEE Transactions on Automatic Control, Volume 38,
Number 5, May 1993.  Briefly, given a scalar S, an M by N matrix
`M(mxn)', and an M by N empty matrix `[](mxn)' (with either one or both
dimensions equal to zero), the following are true:

     s * [](mxn) = [](mxn) * s = [](mxn)

         [](mxn) + [](mxn) = [](mxn)

         [](0xm) *  M(mxn) = [](0xn)

          M(mxn) * [](nx0) = [](mx0)

         [](mx0) * [](0xn) =  0(mxn)

   By default, dimensions of the empty matrix are printed along with the
empty matrix symbol, `[]'.  The built-in variable
`print_empty_dimensions' controls this behavior.

 -- Built-in Variable: print_empty_dimensions
     If the value of `print_empty_dimensions' is nonzero, the
     dimensions of empty matrices are printed along with the empty
     matrix symbol, `[]'.  For example, the expression

          zeros (3, 0)

     will print

          ans = [](3x0)

   Empty matrices may also be used in assignment statements as a
convenient way to delete rows or columns of matrices.  *Note Assignment
Expressions: Assignment Ops.

 -- Built-in Variable: warn_empty_list_elements
     If the value of `warn_empty_list_elements' is nonzero, print a
     warning when an empty matrix is found in a matrix list.  For
     example,

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

     The default value is 0.

   When Octave parses a matrix expression, it examines the elements of
the list to determine whether they are all constants.  If they are, it
replaces the list with a single matrix constant.


File: octave.info,  Node: Ranges,  Next: Logical Values,  Prev: Matrices,  Up: Numeric Data Types

4.2 Ranges
==========

A "range" is a convenient way to write a row vector with evenly spaced
elements.  A range expression is defined by the value of the first
element in the range, an optional value for the increment between
elements, and a maximum value which the elements of the range will not
exceed.  The base, increment, and limit are separated by colons (the
`:' character) and may contain any arithmetic expressions and function
calls.  If the increment is omitted, it is assumed to be 1.  For
example, the range

     1 : 5

defines the set of values `[ 1, 2, 3, 4, 5 ]', and the range

     1 : 3 : 5

defines the set of values `[ 1, 4 ]'.

   Although a range constant specifies a row vector, Octave does _not_
convert range constants to vectors unless it is necessary to do so.
This allows you to write a constant like `1 : 10000' without using
80,000 bytes of storage on a typical 32-bit workstation.

   Note that the upper (or lower, if the increment is negative) bound on
the range is not always included in the set of values, and that ranges
defined by floating point values can produce surprising results because
Octave uses floating point arithmetic to compute the values in the
range.  If it is important to include the endpoints of a range and the
number of elements is known, you should use the `linspace' function
instead (*note Special Utility Matrices::).

   When Octave parses a range expression, it examines the elements of
the expression to determine whether they are all constants.  If they
are, it replaces the range expression with a single range constant.


File: octave.info,  Node: Logical Values,  Next: Predicates for Numeric Objects,  Prev: Ranges,  Up: Numeric Data Types

4.3 Logical Values
==================

 -- Built-in Variable: true
     Logical true value.

 -- Built-in Variable: false
     Logical false value.


File: octave.info,  Node: Predicates for Numeric Objects,  Prev: Logical Values,  Up: Numeric Data Types

4.4 Predicates for Numeric Objects
==================================

 -- Built-in Function:  isnumeric (X)
     Return nonzero if X is a numeric object.

 -- Built-in Function:  isreal (X)
     Return true if X is a real-valued numeric object.

 -- Built-in Function:  iscomplex (X)
     Return true if X is a complex-valued numeric object.

 -- Built-in Function:  ismatrix (A)
     Return 1 if A is a matrix.  Otherwise, return 0.

 -- Function File:  isvector (A)
     Return 1 if A is a vector.  Otherwise, return 0.

 -- Function File:  isscalar (A)
     Return 1 if A is a scalar.  Otherwise, return 0.

 -- Function File:  issquare (X)
     If X is a square matrix, then return the dimension of X.
     Otherwise, return 0.

 -- Function File:  issymmetric (X, TOL)
     If X is symmetric within the tolerance specified by TOL, then
     return the dimension of X.  Otherwise, return 0.  If TOL is
     omitted, use a tolerance equal to the machine precision.

 -- Built-in Functio:  isbool (X)
     Return true if X is a boolean object.


File: octave.info,  Node: Strings,  Next: Data Structures,  Prev: Numeric Data Types,  Up: Top

5 Strings
*********

A "string constant" consists of a sequence of characters enclosed in
either double-quote or single-quote marks.  For example, both of the
following expressions

     "parrot"
     'parrot'

represent the string whose contents are `parrot'.  Strings in Octave
can be of any length.

   Since the single-quote mark is also used for the transpose operator
(*note Arithmetic Ops::) but double-quote marks have no other purpose in
Octave, it is best to use double-quote marks to denote strings.

   Some characters cannot be included literally in a string constant.
You represent them instead with "escape sequences", which are character
sequences beginning with a backslash (`\').

   One use of an escape sequence is to include a double-quote
(single-quote) character in a string constant that has been defined
using double-quote (single-quote) marks.  Since a plain double-quote
would end the string, you must use `\"' to represent a single
double-quote character as a part of the string.  The backslash character
itself is another character that cannot be included normally.  You must
write `\\' to put one backslash in the string.  Thus, the string whose
contents are the two characters `"\' may be written `"\"\\"' or
`'"\\''.  Similarly, the string whose contents are the two characters
`'\' may be written `'\'\\'' or `"'\\"'.

   Another use of backslash is to represent unprintable characters such
as newline.  While there is nothing to stop you from writing most of
these characters directly in a string constant, they may look ugly.

   Here is a table of all the escape sequences used in Octave.  They are
the same as those used in the C programming language.

`\\'
     Represents a literal backslash, `\'.

`\"'
     Represents a literal double-quote character, `"'.

`\''
     Represents a literal single-quote character, `''.

`\0'
     Represents the "nul" character, control-@, ASCII code 0.

`\a'
     Represents the "alert" character, control-g, ASCII code 7.

`\b'
     Represents a backspace, control-h, ASCII code 8.

`\f'
     Represents a formfeed, control-l, ASCII code 12.

`\n'
     Represents a newline, control-j, ASCII code 10.

`\r'
     Represents a carriage return, control-m, ASCII code 13.

`\t'
     Represents a horizontal tab, control-i, ASCII code 9.

`\v'
     Represents a vertical tab, control-k, ASCII code 11.


   Strings may be concatenated using the notation for defining matrices.
For example, the expression

     [ "foo" , "bar" , "baz" ]

produces the string whose contents are `foobarbaz'.  *Note Numeric Data
Types::, for more information about creating matrices.

* Menu:

* Creating Strings::
* Searching and Replacing::
* String Conversions::
* Character Class Functions::


File: octave.info,  Node: Creating Strings,  Next: Searching and Replacing,  Up: Strings

5.1 Creating Strings
====================

 -- Function File:  blanks (N)
     Return a string of N blanks.

 -- Built-in Function:  char (X)
 -- Built-in Function:  char (CELL_ARRAY)
 -- Built-in Function:  char (S1, S2, ...)
     Create a string array from a numeric matrix, cell array, or list of

     If the argument is a numeric matrix, each element of the matrix is
     converted to the corresponding ASCII character.  For example,

          char ([97, 98, 99])
               => "abc"

     If the argument is a cell array of strings, the result is a string
     array with each element corresponding to one element of the cell
     array.

     For multiple string arguments, the result is a string array with
     each element corresponding to the arguments.

     The returned values are padded with blanks as needed to make each
     row of the string array have the same length.

 -- Function File:  int2str (N)
 -- Function File:  num2str (X, PRECISION)
 -- Function File:  num2str (X, FORMAT)
     Convert a number to a string.  These functions are not very
     flexible, but are provided for compatibility with MATLAB.  For
     better control over the results, use `sprintf' (*note Formatted
     Output::).

 -- Function File:  com2str (ZZ, FLG)
     This function has been deprecated.  Use num2str instead.

     Convert complex number to a string.  *Inputs*
    ZZ
          complex number

    FLG
          format flag 0 (default):            -1, 0, 1,   1i,   1 + 0.5i
          1 (for use with zpout): -1, 0, + 1, + 1i, + 1 + 0.5i

 -- Function File:  strcat (S1, S2, ...)
     Return a string containing all the arguments concatenated.  For
     example,

          s = [ "ab"; "cde" ];
          strcat (s, s, s)
          => "ab ab ab "
                  "cdecdecde"

 -- Built-in Variable: string_fill_char
     The value of this variable is used to pad all strings in a string
     matrix to the same length.  It should be a single character.  The
     default value is `" "' (a single space).  For example,

          string_fill_char = "X";
          [ "these"; "are"; "strings" ]
               => "theseXX"
                  "areXXXX"
                  "strings"

 -- Function File:  str2mat (S_1, ..., S_N)
     Return a matrix containing the strings S_1, ..., S_N as its rows.
     Each string is padded with blanks in order to form a valid matrix.

     This function is modelled after MATLAB.  In Octave, you can create
     a matrix of strings by `[S_1; ...; S_N]' even if the strings are
     not all the same length.

 -- Built-in Function:  ischar (A)
     Return 1 if A is a string.  Otherwise, return 0.

 -- Function File:  isstr (A)
     This function has been deprecated.  Use ischar instead.


File: octave.info,  Node: Searching and Replacing,  Next: String Conversions,  Prev: Creating Strings,  Up: Strings

5.2 Searching and Replacing
===========================

 -- Function File:  deblank (S)
     Removes the trailing blanks and nulls from the string S.  If S is
     a matrix, DEBLANK trims each row to the length of longest string.

 -- Function File:  findstr (S, T, OVERLAP)
     Return the vector of all positions in the longer of the two strings
     S and T where an occurrence of the shorter of the two starts.  If
     the optional argument OVERLAP is nonzero, the returned vector can
     include overlapping positions (this is the default).  For example,

          findstr ("ababab", "a")
          => [ 1, 3, 5 ]
          findstr ("abababa", "aba", 0)
          => [ 1, 5 ]

 -- Function File:  index (S, T)
     Return the position of the first occurrence of the string T in the
     string S, or 0 if no occurrence is found.  For example,

          index ("Teststring", "t")
          => 4

     *Caution:*  This function does not work for arrays of strings.

 -- Function File:  rindex (S, T)
     Return the position of the last occurrence of the string T in the
     string S, or 0 if no occurrence is found.  For example,

          rindex ("Teststring", "t")
          => 6

     *Caution:*  This function does not work for arrays of strings.

 -- Function File:  split (S, T)
     Divides the string S into pieces separated by T, returning the
     result in a string array (padded with blanks to form a valid
     matrix).  For example,

          split ("Test string", "t")
          => "Tes "
                  " s  "
                  "ring"

 -- Function File:  strcmp (S1, S2)
     Compares two character strings, returning true if they are the
     same, and false otherwise.

     *Caution:*  For compatibility with MATLAB, Octave's strcmp
     function returns true if the character strings are equal, and false
     otherwise.  This is just the opposite of the corresponding C
     library function.

 -- Function File:  strrep (S, X, Y)
     Replaces all occurrences of the substring X of the string S with
     the string Y.  For example,

          strrep ("This is a test string", "is", "&%$")
          => "Th&%$ &%$ a test string"

 -- Function File:  substr (S, BEG, LEN)
     Return the substring of S which starts at character number BEG and
     is LEN characters long.

     If OFFSET is negative, extraction starts that far from the end of
     the string.  If LEN is omitted, the substring extends to the end
     of S.

     For example,

          substr ("This is a test string", 6, 9)
          => "is a test"

          This function is patterned after AWK.  You can get the same
          result by `S (BEG : (BEG + LEN - 1))'.


File: octave.info,  Node: String Conversions,  Next: Character Class Functions,  Prev: Searching and Replacing,  Up: Strings

5.3 String Conversions
======================

 -- Function File:  hex2dec (S)
     Return the decimal number corresponding to the binary number stored
     in the string S.  For example,

          hex2dec ("1110")
          => 14

     If S is a string matrix, returns a column vector of converted
     numbers, one per row of S.  Invalid rows evaluate to NaN.

 -- Function File:  dec2bin (N, LEN)
     Return a binary number corresponding the nonnegative decimal number
     N, as a string of ones and zeros.  For example,

          dec2bin (14)
          => "1110"

     If N is a vector, returns a string matrix, one row per value,
     padded with leading zeros to the width of the largest value.

     The optional second argument, LEN, specifies the minimum number of
     digits in the result.

 -- Function File:  dec2hex (N, LEN)
     Return the hexadecimal string corresponding to the nonnegative
     integer N.  For example,

          dec2hex (2748)
          => "ABC"

     If N is a vector, returns a string matrix, one row per value,
     padded with leading zeros to the width of the largest value.

     The optional second argument, LEN, specifies the minimum number of
     digits in the result.

 -- Function File:  hex2dec (S)
     Returns the integer corresponding to the hexadecimal number stored
     in the string S.  For example,

          hex2dec ("12B")
          => 299
          hex2dec ("12b")
          => 299

     If S is a string matrix, returns a column vector of converted
     numbers, one per row of S.  Invalid rows evaluate to NaN.

 -- Function File:  dec2base (N, B, LEN)
     Return a string of symbols in base B corresponding to the the
     nonnegative integer N.

          dec2base (123, 3)
          => "11120"

     If N is a vector, return a string matrix with one row per value,
     padded with leading zeros to the width of the largest value.

     If B is a string then the characters of B are used as the symbols
     for the digits of N.  Space (' ') may not be used as a symbol.

          dec2base (123, "aei")
          => "eeeia"

     The optional third argument, LEN, specifies the minimum number of
     digits in the result.

 -- Function File:  base2dec (S, B)
     Convert S from a string of digits of base B into an integer.

          base2dec ("11120", 3)
          => 123

     If S is a matrix, returns a column vector with one value per row
     of S.  If a row contains invalid symbols then the corresponding
     value will be NaN.  Rows are right-justified before converting so
     that trailing spaces are ignored.

     If B is a string, the characters of B are used as the symbols for
     the digits of S. Space (' ') may not be used as a symbol.

          base2dec ("yyyzx", "xyz")
          => 123


 -- Function File:  strjust (S, ["left"|"right"|"center"])
     Shift the non-blank text of S to the left, right or center of the
     string.  If S is a string array, justify each string in the array.
     Null characters are replaced by blanks.  If no justification is
     specified, then all rows are right-justified.

 -- Function File:  str2num (S)
     Convert the string S to a number.

 -- Mapping Function:  toascii (S)
     Return ASCII representation of S in a matrix.  For example,

          toascii ("ASCII")
               => [ 65, 83, 67, 73, 73 ]


 -- Mapping Function:  tolower (S)
     Return a copy of the string S, with each upper-case character
     replaced by the corresponding lower-case one; nonalphabetic
     characters are left unchanged.  For example,

          tolower ("MiXeD cAsE 123")
               => "mixed case 123"

 -- Built-in Function:  toupper (S)
     Return a copy of the string S, with each  lower-case character
     replaced by the corresponding upper-case one; nonalphabetic
     characters are left unchanged.  For example,

          toupper ("MiXeD cAsE 123")
               => "MIXED CASE 123"

 -- Built-in Function:  do_string_escapes (STRING)
     Convert special characters in STRING to their escaped forms.

 -- Built-in Function:  undo_string_escapes (S)
     Converts special characters in strings back to their escaped
     forms.  For example, the expression

          bell = "\a";

     assigns the value of the alert character (control-g, ASCII code 7)
     to the string variable `bell'.  If this string is printed, the
     system will ring the terminal bell (if it is possible).  This is
     normally the desired outcome.  However, sometimes it is useful to
     be able to print the original representation of the string, with
     the special characters replaced by their escape sequences.  For
     example,

          octave:13> undo_string_escapes (bell)
          ans = \a

     replaces the unprintable alert character with its printable
     representation.

 -- Built-in Variable: warn_num_to_str
     If the value of `warn_num_to_str' is nonzero, 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 `warn_num_to_str' is nonzero.  The
     default value is 1.

 -- Built-in Variable: warn_str_to_num
     If the value of `warn_str_to_num' is nonzero, 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 `warn_str_to_num' is nonzero.  The
     default value is 0.

 -- Built-in Variable: warn_single_quote_string
     Print warning if a signle quote character is used to introduce a
     string constant.


File: octave.info,  Node: Character Class Functions,  Prev: String Conversions,  Up: Strings

5.4 Character Class Functions
=============================

Octave also provides the following character class test functions
patterned after the functions in the standard C library.  They all
operate on string arrays and return matrices of zeros and ones.
Elements that are nonzero indicate that the condition was true for the
corresponding character in the string array.  For example,

     isalpha ("!Q@WERT^Y&")
          => [ 0, 1, 0, 1, 1, 1, 1, 0, 1, 0 ]

 -- Mapping Function:  isalnum (S)
     Return 1 for characters that are letters or digits (`isalpha (S)'
     or `isdigit (S)' is true).

 -- Mapping Function:  isalpha (S)
 -- Mapping Function:  isletter (S)
     Return true for characters that are letters (`isupper (S)' or
     `islower (S)' is true).

 -- Mapping Function:  isascii (S)
     Return 1 for characters that are ASCII (in the range 0 to 127
     decimal).

 -- Mapping Function:  iscntrl (S)
     Return 1 for control characters.

 -- Mapping Function:  isdigit (S)
     Return 1 for characters that are decimal digits.

 -- Mapping Function:  isgraph (S)
     Return 1 for printable characters (but not the space character).

 -- Mapping Function:  islower (S)
     Return 1 for characters that are lower case letters.

 -- Mapping Function:  isprint (S)
     Return 1 for printable characters (including the space character).

 -- Mapping Function:  ispunct (S)
     Return 1 for punctuation characters.

 -- Mapping Function:  isspace (S)
     Return 1 for whitespace characters (space, formfeed, newline,
     carriage return, tab, and vertical tab).

 -- Mapping Function:  isupper (S)
     Return 1 for upper case letters.

 -- Mapping Function:  isxdigit (S)
     Return 1 for characters that are hexadecimal digits.


File: octave.info,  Node: Data Structures,  Next: Containers,  Prev: Strings,  Up: Top

6 Data Structures
*****************

Octave includes support for organizing data in structures.  The current
implementation uses an associative array with indices limited to
strings, but the syntax is more like C-style structures.  Here are some
examples of using data structures in Octave.

   Elements of structures can be of any value type.  For example, the
three expressions

     x.a = 1
     x.b = [1, 2; 3, 4]
     x.c = "string"

create a structure with three elements.  To print the value of the
structure, you can type its name, just as for any other variable:

     octave:2> x
     x =
     {
       a = 1
       b =

         1  2
         3  4

       c = string
     }

Note that Octave may print the elements in any order.

   Structures may be copied.

     octave:1> y = x
     y =
     {
       a = 1
       b =

         1  2
         3  4

       c = string
     }

   Since structures are themselves values, structure elements may
reference other structures.  The following statements change the value
of the element `b' of the structure `x' to be a data structure
containing the single element `d', which has a value of 3.

     octave:1> x.b.d = 3
     x.b.d = 3
     octave:2> x.b
     ans =
     {
       d = 3
     }
     octave:3> x
     x =
     {
       a = 1
       b =
       {
         d = 3
       }

       c = string
     }

   Note that when Octave prints the value of a structure that contains
other structures, only a few levels are displayed.  For example,

     octave:1> a.b.c.d.e = 1;
     octave:2> a
     a =
     {
       b =
       {
         c =
         {
           d: 1x1 struct
         }
       }
     }

This prevents long and confusing output from large deeply nested
structures.

 -- Built-in Variable: struct_levels_to_print
     You can tell Octave how many structure levels to display by
     setting the built-in variable `struct_levels_to_print'.  The
     default value is 2.

   Functions can return structures.  For example, the following function
separates the real and complex parts of a matrix and stores them in two
elements of the same structure variable.

     octave:1> function y = f (x)
     > y.re = real (x);
     > y.im = imag (x);
     > endfunction

   When called with a complex-valued argument, `f' returns the data
structure containing the real and imaginary parts of the original
function argument.

     octave:2> f (rand (2) + rand (2) * I);
     ans =
     {
       im =

         0.26475  0.14828
         0.18436  0.83669

       re =

         0.040239  0.242160
         0.238081  0.402523
     }

   Function return lists can include structure elements, and they may be
indexed like any other variable.  For example,

     octave:1> [ x.u, x.s(2:3,2:3), x.v ] = svd ([1, 2; 3, 4])
     x.u =

       -0.40455  -0.91451
       -0.91451   0.40455

     x.s =

       0.00000  0.00000  0.00000
       0.00000  5.46499  0.00000
       0.00000  0.00000  0.36597

     x.v =

       -0.57605   0.81742
       -0.81742  -0.57605

   It is also possible to cycle through all the elements of a structure
in a loop, using a special form of the `for' statement (*note The for
Statement::)

   The following functions are available to give you information about
structures.

 -- Built-in Function:  isstruct (EXPR)
     Return 1 if the value of the expression EXPR is a structure.

 -- Built-in Function:  fieldnames (STRUCT)
     Return a cell array of strings naming the elements of the structure
     STRUCT.  It is an error to call `fieldnames' with an argument that
     is not a structure.

 -- Built-in Function:  isfield (EXPR, NAME)
     Return true if the expression EXPR is a structure and it includes
     an element named NAME.  The first argument must be a structure and
     the second must be a string.


File: octave.info,  Node: Containers,  Next: I/O Streams,  Prev: Data Structures,  Up: Top

7 Containers
************

* Menu:

* Lists::
* Cell Arrays::


File: octave.info,  Node: Lists,  Next: Cell Arrays,  Up: Containers

7.1 Lists
=========

 -- Built-in Function:  list (A1, A2, ...)
     Create a new list with elements given by the arguments A1, A2, ....

 -- Built-in Function:  nth (LIST, N)
     Return the N-th element of LIST.

 -- Built-in Function:  append (LIST, A1, A2, ...)
     Return a new list created by appending A1, A1, ..., to LIST.  If
     any of the arguments to be appended is a list, its elements are
     appended individually.  For example,

          x = list (1, 2);
          y = list (3, 4);
          append (x, y);

     results in the list containing the four elements `(1 2 3 4)', not
     a list containing the three elements `(1 2 (3 4))'.

 -- Built-in Function:  reverse (LIST)
     Return a new list created by reversing the elements of LIST.

 -- Built-in Function:  splice (LIST_1, OFFSET, LENGTH, LIST_2)
     Replace LENGTH elements of LIST_1 beginning at OFFSET with the
     contents of LIST_2 (if any).  If LENGTH is omitted, all elements
     from OFFSET to the end of LIST_1 are replaced.  As a special case,
     if OFFSET is one greater than the length of LIST_1 and LENGTH is
     0, splice is equivalent to `append (LIST_1, LIST_2)'.

 -- Built-in Function:  islist (X)
     Return nonzero if X is a list.


File: octave.info,  Node: Cell Arrays,  Prev: Lists,  Up: Containers

7.2 Cell Arrays
===============

 -- Built-in Function:  cell (X)
 -- Built-in Function:  cell (N, M)
     Create a new cell array object.  If invoked with a single scalar
     argument, `cell' returns a square cell array with the dimension
     specified.  If you supply two scalar arguments, `cell' takes them
     to be the number of rows and columns.  If given a vector with two
     elements, `cell' uses the values of the elements as the number of
     rows and columns, respectively.

 -- Built-in Function:  cellstr (STRING)
     Create a new cell array object from the elements of the string
     array STRING.

 -- Built-in Function:  iscell (X)
     Return true if X is a cell array object.  Otherwise, return false.


File: octave.info,  Node: I/O Streams,  Next: Variables,  Prev: Containers,  Up: Top

8 I/O Streams
*************

 -- Built-in Function:  isstream (X)
     Return true if X is a stream object.  Otherwise, return false.


File: octave.info,  Node: Variables,  Next: Expressions,  Prev: I/O Streams,  Up: Top

9 Variables
***********

Variables let you give names to values and refer to them later.  You
have already seen variables in many of the examples.  The name of a
variable must be a sequence of letters, digits and underscores, but it
may not begin with a digit.  Octave does not enforce a limit on the
length of variable names, but it is seldom useful to have variables
with names longer than about 30 characters.  The following are all
valid variable names

     x
     x15
     __foo_bar_baz__
     fucnrdthsucngtagdjb

However, names like `__foo_bar_baz__' that begin and end with two
underscores are understood to be reserved for internal use by Octave.
You should not use them in code you write, except to access Octave's
documented internal variables and built-in symbolic constants.

   Case is significant in variable names.  The symbols `a' and `A' are
distinct variables.

   A variable name is a valid expression by itself.  It represents the
variable's current value.  Variables are given new values with
"assignment operators" and "increment operators".  *Note Assignment
Expressions: Assignment Ops.

   A number of variables have special built-in meanings.  For example,
`ans' holds the current working directory, and `pi' names the ratio of
the circumference of a circle to its diameter. *Note Summary of
Built-in Variables::, for a list of all the predefined variables.  Some
of these built-in symbols are constants and may not be changed.  Others
can be used and assigned just like all other variables, but their values
are also used or changed automatically by Octave.

   Variables in Octave do not have fixed types, so it is possible to
first store a numeric value in a variable and then to later use the
same name to hold a string value in the same program.  Variables may
not be used before they have been given a value.  Doing so results in
an error.

* Menu:

* Global Variables::
* Persistent Variables::
* Status of Variables::
* Summary of Built-in Variables::
* Defaults from the Environment::


File: octave.info,  Node: Global Variables,  Next: Persistent Variables,  Up: Variables

9.1 Global Variables
====================

A variable that has been declared "global" may be accessed from within
a function body without having to pass it as a formal parameter.

   A variable may be declared global using a `global' declaration
statement.  The following statements are all global declarations.

     global a
     global a b
     global c = 2
     global d = 3 e f = 5

   A global variable may only be initialized once in a `global'
statement.  For example, after executing the following code

     global gvar = 1
     global gvar = 2

the value of the global variable `gvar' is 1, not 2.

   It is necessary declare a variable as global within a function body
in order to access it.  For example,

     global x
     function f ()
       x = 1;
     endfunction
     f ()

does _not_ set the value of the global variable `x' to 1.  In order to
change the value of the global variable `x', you must also declare it
to be global within the function body, like this

     function f ()
       global x;
       x = 1;
     endfunction

   Passing a global variable in a function parameter list will make a
local copy and not modify the global value.  For example, given the
function

     function f (x)
       x = 0
     endfunction

and the definition of `x' as a global variable at the top level,

     global x = 13

the expression

     f (x)

will display the value of `x' from inside the function as 0, but the
value of `x' at the top level remains unchanged, because the function
works with a _copy_ of its argument.

 -- Built-in Function:  isglobal (NAME)
     Return 1 if NAME is globally visible.  Otherwise, return 0.  For
     example,

          global x
          isglobal ("x")
               => 1


File: octave.info,  Node: Persistent Variables,  Next: Status of Variables,  Prev: Global Variables,  Up: Variables

9.2 Persistent Variables
========================

A variable that has been declared "persistent" within a function will
retain its contents in memory between subsequent calls to the same
function. The difference between persistent variables and global
variables is that persistent variables are local in scope to a
particular function and are not visible elsewhere.

   A variable may be declared persistent using a `persistent'
declaration statement.  The following statements are all persistent
declarations.

     persistent a
     persistent a b
     persistent c = 2
     persistent d = 3 e f = 5

   The behavior of persistent variables is equivalent to the behavior of
static variables in C. The command `static' in octave is also
recognized and is equivalent to `persistent'. Unlike global variables,
every initialization statement will re-initialize the variable. For
example, after executing the following code

     persistent pvar = 1
     persistent pvar = 2

the value of the persistent variable `pvar' is 2.


File: octave.info,  Node: Status of Variables,  Next: Summary of Built-in Variables,  Prev: Persistent Variables,  Up: Variables

9.3 Status of Variables
=======================

 -- Command: clear [-x] pattern ...
     Delete the names matching the given patterns from the symbol
     table.  The pattern may contain 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.

     For example, the command

          clear foo b*r

     clears the name `foo' and all names that begin with the letter `b'
     and end with the letter `r'.

     If `clear' is called without any arguments, all user-defined
     variables (local and global) are cleared from the symbol table.  If
     `clear' is called with at least one argument, only the visible
     names matching the arguments are cleared.  For example, suppose
     you have defined a function `foo', and then hidden it by
     performing the assignment `foo = 2'.  Executing the command `clear
     foo' once will clear the variable definition and restore the
     definition of `foo' as a function.  Executing `clear foo' a second
     time will clear the function definition.

     With -x, clear the variables that don't match the patterns.

     This command may not be used within a function body.

 -- Command: who options pattern ...
 -- Command: whos options pattern ...
     List currently defined symbols matching the given patterns.  The
     following are valid options.  They may be shortened to one
     character but may not be combined.

    `-all'
          List all currently defined symbols.

    `-builtins'
          List built-in variables and functions.  This includes all
          currently compiled function files, but does not include all
          function files that are in the `LOADPATH'.

    `-functions'
          List user-defined functions.

    `-long'
          Print a long listing including the type and dimensions of any
          symbols.  The symbols in the first column of output indicate
          whether it is possible to redefine the symbol, and whether it
          is possible for it to be cleared.

    `-variables'
          List user-defined variables.

     Valid patterns are the same as described for the `clear' command
     above.  If no patterns are supplied, all symbols from the given
     category are listed.  By default, only user defined functions and
     variables visible in the local scope are displayed.

     The command `whos' is equivalent to `who -long'.

 -- Command: whos options pattern ...
     See who.

 -- Built-in Variable: whos_line_format
     This string decides in what order attributtes of variables are to
     be printed.  The following commands are used:
    `%b'
          Prints number of bytes occupied by variables.

    `%e'
          Prints elements held by variables.

    `%n'
          Prints variable names.

    `%p'
          Prints protection attributtes of variables.

    `%s'
          Prints dimensions of variables.

    `%t'
          Prints type names of variables.

     Every command may also have a modifier:
    `l'
          Left alignment.

    `r'
          Right alignment (this is the default).

    `c'
          Centered (may only be applied to command %s).

     A command is composed like this:
     %[modifier]<command>[:size_of_parameter[:center-specific[:print_dims[:balance]]]];

     Command and modifier is already explained. Size_of_parameter tells
     how many columns the parameter will need for printing.  print_dims
     tells how many dimensions to print. If number of dimensions
     exceeds print_dims, dimensions will be printed like x-D.
     center-specific and print_dims may only be applied to command %s.
     A negative value for print_dims will cause Octave to print all
     dimensions whatsoever.  balance specifies the offset for printing
     of the dimensions string.

     Default format is "  %p:4; %ln:6; %cs:16:6:8:1;  %rb:12;
     %lt:-1;\n".

 -- Built-in Function:  exist (NAME, TYPE)
     Return 1 if the name exists as a variable, 2 if the name (after
     appending `.m') is a function file in Octave's LOADPATH, 3 if the
     name is a `.oct' file in Octave's LOADPATH, 5 if the name is a
     built-in function, 7 if the name is a directory, 101 if the name is
     a built-in variable, 102 if the name is a built-in constant, or 103
     if the name is a function not associated with a file (entered on
     the command line).

     Otherwise, return 0.

     This function also returns 2 if a regular file called NAME exists
     in Octave's `LOADPATH'.  If you want information about other types
     of files, you should use some combination of the functions
     `file_in_path' and `stat' instead.

     If the optional argument TYPE is supplied, check only for symbols
     of the specified type.  Valid types are

    `"var"'
          Check only for variables.

    `"builtin"'
          Check only for built-in functions.

    `"file"'
          Check only for files.

    `"dir"'
          Check only for directories.

 -- Built-in Function:  document (SYMBOL, TEXT)
     Set the documentation string for SYMBOL to TEXT.

 -- Command: type options name ...
     Display the definition of each NAME that refers to a function.

     Normally also displays if each NAME is user-defined or builtin;
     the `-q' option suppresses this behaviour.

     Currently, Octave can only display functions that can be compiled
     cleanly, because it uses its internal representation of the
     function to recreate the program text.

     Comments are not displayed because Octave's parser currently
     discards them as it converts the text of a function file to its
     internal representation.  This problem may be fixed in a future
     release.

 -- Command: which name ...
     Display the type of each NAME.  If NAME is defined from a function
     file, the full name of the file is also displayed.


File: octave.info,  Node: Summary of Built-in Variables,  Next: Defaults from the Environment,  Prev: Status of Variables,  Up: Variables

9.4 Summary of Built-in Variables
=================================

Here is a summary of all of Octave's built-in variables along with
cross references to additional information and their default values.  In
the following table OCTAVE-HOME stands for the root directory where all
of Octave is installed (the default is `/usr/local', VERSION stands for
the Octave version number (for example, 2.1.x) and ARCH stands for the
type of system for which Octave was compiled (for example,
`i586-pc-linux-gnu').

`DEFAULT_LOADPATH'
     *Note Function Files::.

     Default value: `".:OCTAVE-HOME/lib/VERSION"'.

`EDITOR'
     *Note Commands For History::.

     Default value: `"emacs"'.

`EXEC_PATH'
     *Note Controlling Subprocesses::.

     Default value: `":$PATH"'.

`INFO_FILE'
     *Note Getting Help::.

     Default value: `"OCTAVE-HOME/info/octave.info"'.

`INFO_PROGRAM'
     *Note Getting Help::.

     Default value:
     `"OCTAVE-HOME/libexec/octave/VERSION/exec/ARCH/info"'.

`LOADPATH'
     *Note Function Files::.

     Default value: `":"', which tells Octave to use the directories
     specified by the built-in variable `DEFAULT_LOADPATH'.

`OCTAVE_HOME'
     Default value: `"/usr/local"'.

`PAGER'
     *Note Input and Output::.

     Default value: `"less", or "more"'.

`PS1'
     *Note Customizing the Prompt::.

     Default value: `"\s:\#> "'.

`PS2'
     *Note Customizing the Prompt::.

     Default value: `"> "'.

`PS4'
     *Note Customizing the Prompt::.

     Default value: `"+ "'.

`automatic_replot'
     *Note Two-Dimensional Plotting::.

     Default value: 0.

`beep_on_error'
     *Note Error Handling::.

     Default value: 0.

`completion_append_char'
     *Note Commands For Completion::.

     Default value: `" "'.

`default_save_format'
     *Note Simple File I/O::.

     Default value: `"ascii"'.

`crash_dumps_octave_core'
     *Note Simple File I/O::.

     Default value: 1.

`fixed_point_format'
     *Note Matrices::.

     Default value: 0.

`gnuplot_binary'
     *Note Three-Dimensional Plotting::.

     Default value: `"gnuplot"'.

`history_file'
     *Note Commands For History::.

     Default value: `"~/.octave_hist"'.

`history_size'
     *Note Commands For History::.

     Default value: 1024.

`ignore_function_time_stamp'
     *Note Function Files::.

     Default value: `"system"'.

`max_recursion_depth'
     *Note Recursion::.

     Default value: 256.

`output_max_field_width'
     *Note Matrices::.

     Default value: 10.

`output_precision'
     *Note Matrices::.

     Default value: 5.

`page_screen_output'
     *Note Input and Output::.

     Default value: 1.

`print_answer_id_name'
     *Note Terminal Output::.

     Default value: 1.

`print_empty_dimensions'
     *Note Empty Matrices::.

     Default value: 1.

`return_last_computed_value'
     *Note Returning From a Function::.

     Default value: 0.

`save_precision'
     *Note Simple File I/O::.

     Default value: 17.

`saving_history'
     *Note Commands For History::.

     Default value: 1.

`sighup_dumps_octave_core'
     *Note Simple File I/O::.

     Default value: 1.

`sigterm_dumps_octave_core'
     *Note Simple File I/O::.

     Default value: 1.

`silent_functions'
     *Note Defining Functions::.

     Default value: 0.

`split_long_rows'
     *Note Matrices::.

     Default value: 1.

`struct_levels_to_print'
     *Note Data Structures::.

     Default value: 2.

`suppress_verbose_help_message'
     *Note Getting Help::.

     Default value: 1.

`warn_assign_as_truth_value'
     *Note The if Statement::.

     Default value: 1.

`warn_comma_in_global_decl'
     *Note Global Variables::.

     Default value: 1.

`warn_divide_by_zero'
     *Note Arithmetic Ops::.

     Default value: 1.

`warn_empty_list_elements'
     *Note Empty Matrices::.

     Default value: 0.

`warn_fortran_indexing'
     *Note Index Expressions::.

     Default value: 0.

`warn_function_name_clash'
     *Note Function Files::.

     Default value: 1.

`warn_imag_to_real'
     *Note Special Utility Matrices::.

     Default value: 0.

`warn_missing_semicolon'
     *Note Defining Functions::.

     Default value: 0.

`warn_neg_dim_as_zero'
     *Note Special Utility Matrices::.

     Default value: 0.

`warn_num_to_str'
     *Note String Conversions::.

     Default value: 1.

`warn_reload_forces_clear'
     *Note Dynamically Linked Functions::.

     Default value: 1.

`warn_resize_on_range_error'
     *Note Index Expressions::.

     Default value: 0.

`warn_separator_insert'
     *Note Matrices::.

     Default value: 0.

`warn_single_quote_string'
     *Note String Conversions::.

     Default value: 0.

`warn_str_to_num'
     *Note String Conversions::.

     Default value: 0.

`warn_undefined_return_values'
     *Note Multiple Return Values::.

     Default value: 0.

`warn_variable_switch_label'
     *Note The switch Statement::.

     Default value: 0.


File: octave.info,  Node: Defaults from the Environment,  Prev: Summary of Built-in Variables,  Up: Variables

9.5 Defaults from the Environment
=================================

Octave uses the values of the following environment variables to set the
default values for the corresponding built-in variables.  In addition,
the values from the environment may be overridden by command-line
arguments.  *Note Command Line Options::.

`EDITOR'
     *Note Commands For History::.

     Built-in variable: `EDITOR'.

`OCTAVE_EXEC_PATH'
     *Note Controlling Subprocesses::.

     Built-in variable: `EXEC_PATH'.  Command-line argument:
     `--exec-path'.

`OCTAVE_PATH'
     *Note Function Files::.

     Built-in variable: `LOADPATH'.  Command-line argument: `--path'.

`OCTAVE_INFO_FILE'
     *Note Getting Help::.

     Built-in variable: `INFO_FILE'.  Command-line argument:
     `--info-file'.

`OCTAVE_INFO_PROGRAM'
     *Note Getting Help::.

     Built-in variable: `INFO_PROGRAM'.  Command-line argument:
     `--info-program'.

`OCTAVE_HISTSIZE'
     *Note Commands For History::.

     Built-in variable: `history_size'.

`OCTAVE_HISTFILE'
     *Note Commands For History::.

     Built-in variable: `history_file'.


File: octave.info,  Node: Expressions,  Next: Evaluation,  Prev: Variables,  Up: Top

10 Expressions
**************

Expressions are the basic building block of statements in Octave.  An
expression evaluates to a value, which you can print, test, store in a
variable, pass to a function, or assign a new value to a variable with
an assignment operator.

   An expression can serve as a statement on its own.  Most other kinds
of statements contain one or more expressions which specify data to be
operated on.  As in other languages, expressions in Octave include
variables, array references, constants, and function calls, as well as
combinations of these with various operators.

* Menu:

* Index Expressions::
* Calling Functions::
* Arithmetic Ops::
* Comparison Ops::
* Boolean Expressions::
* Assignment Ops::
* Increment Ops::
* Operator Precedence::


File: octave.info,  Node: Index Expressions,  Next: Calling Functions,  Up: Expressions

10.1 Index Expressions
======================

An "index expression" allows you to reference or extract selected
elements of a matrix or vector.

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

   Vectors are indexed using a single expression.  Matrices may be
indexed using one or two indices (a warning is issued if a single index
is used unless the value of the built-in variable
`warn_fortran_indexing' is zero).

 -- Built-in Variable: warn_fortran_indexing
     If the value of `warn_fortran_indexing' is nonzero, a warning is
     printed for expressions which select elements of a two-dimensional
     matrix using a single index.  The default value is 0.

   Given the matrix

     a = [1, 2; 3, 4]

all of the following expressions are equivalent

     a (1, [1, 2])
     a (1, 1:2)
     a (1, :)

and select the first row of the matrix.

   Indexing a scalar with a vector of ones can be used to create a
vector the same size as the index vector, with each element equal to
the value of the original scalar.  For example, the following statements

     a = 13;
     a ([1, 1, 1, 1])

produce a vector whose four elements are all equal to 13.

   Similarly, indexing a scalar with two vectors of ones can be used to
create a matrix.  For example the following statements

     a = 13;
     a ([1, 1], [1, 1, 1])

create a 2 by 3 matrix with all elements equal to 13.

   This is an obscure notation and should be avoided.  It is better to
use the function `ones' to generate a matrix of the appropriate size
whose elements are all one, and then to scale it to produce the desired
result.  *Note Special Utility Matrices::.

 -- Built-in Variable: warn_resize_on_range_error
     If the value of `warn_resize_on_range_error' is nonzero, print a
     warning when a matrix is resized by an indexed assignment with
     indices outside the current bounds.  The default value is 0.

   Note that it is quite inefficient to create a vector using a loop
like the one shown in the example above.  In this particular case, it
would have been much more efficient to use the expression

     a = sqrt (1:10);

thus avoiding the loop entirely.  In cases where a loop is still
required, or a number of values must be combined to form a larger
matrix, it is generally much faster to set the size of the matrix first,
and then insert elements using indexing commands.  For example, given a
matrix `a',

     [nr, nc] = size (a);
     x = zeros (nr, n * nc);
     for i = 1:n
       x(:,(i-1)*nc+1:i*nc) = a;
     endfor

is considerably faster than

     x = a;
     for i = 1:n-1
       x = [x, a];
     endfor

particularly for large matrices because Octave does not have to
repeatedly resize the result.


File: octave.info,  Node: Calling Functions,  Next: Arithmetic Ops,  Prev: Index Expressions,  Up: Expressions

10.2 Calling Functions
======================

A "function" is a name for a particular calculation.  Because it has a
name, you can ask for it by name at any point in the program.  For
example, the function `sqrt' computes the square root of a number.

   A fixed set of functions are "built-in", which means they are
available in every Octave program.  The `sqrt' function is one of
these.  In addition, you can define your own functions.  *Note
Functions and Scripts::, for information about how to do this.

   The way to use a function is with a "function call" expression,
which consists of the function name followed by a list of "arguments"
in parentheses. The arguments are expressions which give the raw
materials for the calculation that the function will do.  When there is
more than one argument, they are separated by commas.  If there are no
arguments, you can omit the parentheses, but it is a good idea to
include them anyway, to clearly indicate that a function call was
intended.  Here are some examples:

     sqrt (x^2 + y^2)      # One argument
     ones (n, m)           # Two arguments
     rand ()               # No arguments

   Each function expects a particular number of arguments.  For
example, the `sqrt' function must be called with a single argument, the
number to take the square root of:

     sqrt (ARGUMENT)

   Some of the built-in functions take a variable number of arguments,
depending on the particular usage, and their behavior is different
depending on the number of arguments supplied.

   Like every other expression, the function call has a value, which is
computed by the function based on the arguments you give it.  In this
example, the value of `sqrt (ARGUMENT)' is the square root of the
argument.  A function can also have side effects, such as assigning the
values of certain variables or doing input or output operations.

   Unlike most languages, functions in Octave may return multiple
values.  For example, the following statement

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

computes the singular value decomposition of the matrix `a' and assigns
the three result matrices to `u', `s', and `v'.

   The left side of a multiple assignment expression is itself a list of
expressions, and is allowed to be a list of variable names or index
expressions.  See also *Note Index Expressions::, and *Note Assignment
Ops::.

* Menu:

* Call by Value::
* Recursion::


File: octave.info,  Node: Call by Value,  Next: Recursion,  Up: Calling Functions

10.2.1 Call by Value
--------------------

In Octave, unlike Fortran, function arguments are passed by value, which
means that each argument in a function call is evaluated and assigned to
a temporary location in memory before being passed to the function.
There is currently no way to specify that a function parameter should be
passed by reference instead of by value.  This means that it is
impossible to directly alter the value of function parameter in the
calling function.  It can only change the local copy within the function
body.  For example, the function

     function f (x, n)
       while (n-- > 0)
         disp (x);
       endwhile
     endfunction

displays the value of the first argument N times.  In this function,
the variable N is used as a temporary variable without having to worry
that its value might also change in the calling function.  Call by
value is also useful because it is always possible to pass constants
for any function parameter without first having to determine that the
function will not attempt to modify the parameter.

   The caller may use a variable as the expression for the argument, but
the called function does not know this: it only knows what value the
argument had.  For example, given a function called as

     foo = "bar";
     fcn (foo)

you should not think of the argument as being "the variable `foo'."
Instead, think of the argument as the string value, `"bar"'.

   Even though Octave uses pass-by-value semantics for function
arguments, values are not copied unnecessarily.  For example,

     x = rand (1000);
     f (x);

does not actually force two 1000 by 1000 element matrices to exist
_unless_ the function `f' modifies the value of its argument.  Then
Octave must create a copy to avoid changing the value outside the scope
of the function `f', or attempting (and probably failing!) to modify
the value of a constant or the value of a temporary result.


File: octave.info,  Node: Recursion,  Prev: Call by Value,  Up: Calling Functions

10.2.2 Recursion
----------------

With some restrictions(1), recursive function calls are allowed.  A
"recursive function" is one which calls itself, either directly or
indirectly.  For example, here is an inefficient(2) way to compute the
factorial of a given integer:

     function retval = fact (n)
       if (n > 0)
         retval = n * fact (n-1);
       else
         retval = 1;
       endif
     endfunction

   This function is recursive because it calls itself directly.  It
eventually terminates because each time it calls itself, it uses an
argument that is one less than was used for the previous call.  Once the
argument is no longer greater than zero, it does not call itself, and
the recursion ends.

   The built-in variable `max_recursion_depth' specifies a limit to the
recursion depth and prevents Octave from recursing infinitely.

 -- Built-in Variable: max_recursion_depth
     Limit the number of times a function may be called recursively.
     If the limit is exceeded, an error message is printed and control
     returns to the top level.

     The default value is 256.

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

   (1) Some of Octave's function are implemented in terms of functions
that cannot be called recursively.  For example, the ODE solver `lsode'
is ultimately implemented in a Fortran subroutine that cannot be called
recursively, so `lsode' should not be called either directly or
indirectly from within the user-supplied function that `lsode'
requires.  Doing so will result in undefined behavior.

   (2) It would be much better to use `prod (1:n)', or `gamma (n+1)'
instead, after first checking to ensure that the value `n' is actually a
positive integer.


File: octave.info,  Node: Arithmetic Ops,  Next: Comparison Ops,  Prev: Calling Functions,  Up: Expressions

10.3 Arithmetic Operators
=========================

The following arithmetic operators are available, and work on scalars
and matrices.

`X + Y'
     Addition.  If both operands are matrices, the number of rows and
     columns must both agree.  If one operand is a scalar, its value is
     added to all the elements of the other operand.

`X .+ Y'
     Element by element addition.  This operator is equivalent to `+'.

`X - Y'
     Subtraction.  If both operands are matrices, the number of rows and
     columns of both must agree.

`X .- Y'
     Element by element subtraction.  This operator is equivalent to
     `-'.

`X * Y'
     Matrix multiplication.  The number of columns of X must agree with
     the number of rows of Y.

`X .* Y'
     Element by element multiplication.  If both operands are matrices,
     the number of rows and columns must both agree.

`X / Y'
     Right division.  This is conceptually equivalent to the expression

          (inverse (y') * x')'

     but it is computed without forming the inverse of Y'.

     If the system is not square, or if the coefficient matrix is
     singular, a minimum norm solution is computed.

`X ./ Y'
     Element by element right division.

`X \ Y'
     Left division.  This is conceptually equivalent to the expression

          inverse (x) * y

     but it is computed without forming the inverse of X.

     If the system is not square, or if the coefficient matrix is
     singular, a minimum norm solution is computed.

`X .\ Y'
     Element by element left division.  Each element of Y is divided by
     each corresponding element of X.

`X ^ Y'
`X ** Y'
     Power operator.  If X and Y are both scalars, this operator
     returns X raised to the power Y.  If X is a scalar and Y is a
     square matrix, the result is computed using an eigenvalue
     expansion.  If X is a square matrix. the result is computed by
     repeated multiplication if Y is an integer, and by an eigenvalue
     expansion if Y is not an integer.  An error results if both X and
     Y are matrices.

     The implementation of this operator needs to be improved.

`X .^ Y'

`X .** Y'
     Element by element power operator.  If both operands are matrices,
     the number of rows and columns must both agree.

`-X'
     Negation.

`+X'
     Unary plus.  This operator has no effect on the operand.

`X''
     Complex conjugate transpose.  For real arguments, this operator is
     the same as the transpose operator.  For complex arguments, this
     operator is equivalent to the expression

          conj (x.')

`X.''
     Transpose.

   Note that because Octave's element by element operators begin with a
`.', there is a possible ambiguity for statements like

     1./m

because the period could be interpreted either as part of the constant
or as part of the operator.  To resolve this conflict, Octave treats the
expression as if you had typed

     (1) ./ m

and not

     (1.) / m

Although this is inconsistent with the normal behavior of Octave's
lexer, which usually prefers to break the input into tokens by
preferring the longest possible match at any given point, it is more
useful in this case.

 -- Built-in Variable: warn_divide_by_zero
     If the value of `warn_divide_by_zero' is nonzero, a warning is
     issued when Octave encounters a division by zero.  If the value is
     0, the warning is omitted.  The default value is 1.


File: octave.info,  Node: Comparison Ops,  Next: Boolean Expressions,  Prev: Arithmetic Ops,  Up: Expressions

10.4 Comparison Operators
=========================

"Comparison operators" compare numeric values for relationships such as
equality.  They are written using _relational operators_.

   All of Octave's comparison operators return a value of 1 if the
comparison is true, or 0 if it is false.  For matrix values, they all
work on an element-by-element basis.  For example,

     [1, 2; 3, 4] == [1, 3; 2, 4]
          =>  1  0
              0  1

   If one operand is a scalar and the other is a matrix, the scalar is
compared to each element of the matrix in turn, and the result is the
same size as the matrix.

`X < Y'
     True if X is less than Y.

`X <= Y'
     True if X is less than or equal to Y.

`X == Y'
     True if X is equal to Y.

`X >= Y'
     True if X is greater than or equal to Y.

`X > Y'
     True if X is greater than Y.

`X != Y'
`X ~= Y'
`X <> Y'
     True if X is not equal to Y.

   String comparisons may also be performed with the `strcmp' function,
not with the comparison operators listed above.  *Note Strings::.


File: octave.info,  Node: Boolean Expressions,  Next: Assignment Ops,  Prev: Comparison Ops,  Up: Expressions

10.5 Boolean Expressions
========================

* Menu:

* Element-by-element Boolean Operators::
* Short-circuit Boolean Operators::


File: octave.info,  Node: Element-by-element Boolean Operators,  Next: Short-circuit Boolean Operators,  Up: Boolean Expressions

10.5.1 Element-by-element Boolean Operators
-------------------------------------------

An "element-by-element boolean expression" is a combination of
comparison expressions using the boolean operators "or" (`|'), "and"
(`&'), and "not" (`!'), along with parentheses to control nesting.  The
truth of the boolean expression is computed by combining the truth
values of the corresponding elements of the component expressions.  A
value is considered to be false if it is zero, and true otherwise.

   Element-by-element boolean expressions can be used wherever
comparison expressions can be used.  They can be used in `if' and
`while' statements.  However, if a matrix value used as the condition
in an `if' or `while' statement is only true if _all_ of its elements
are nonzero.

   Like comparison operations, each element of an element-by-element
boolean expression also has a numeric value (1 if true, 0 if false) that
comes into play if the result of the boolean expression is stored in a
variable, or used in arithmetic.

   Here are descriptions of the three element-by-element boolean
operators.

`BOOLEAN1 & BOOLEAN2'
     Elements of the result are true if both corresponding elements of
     BOOLEAN1 and BOOLEAN2 are true.

`BOOLEAN1 | BOOLEAN2'
     Elements of the result are true if either of the corresponding
     elements of BOOLEAN1 or BOOLEAN2 is true.

`! BOOLEAN'
`~ BOOLEAN'
     Each element of the result is true if the corresponding element of
     BOOLEAN is false.

   For matrix operands, these operators work on an element-by-element
basis.  For example, the expression

     [1, 0; 0, 1] & [1, 0; 2, 3]

returns a two by two identity matrix.

   For the binary operators, the dimensions of the operands must
conform if both are matrices.  If one of the operands is a scalar and
the other a matrix, the operator is applied to the scalar and each
element of the matrix.

   For the binary element-by-element boolean operators, both
subexpressions BOOLEAN1 and BOOLEAN2 are evaluated before computing the
result.  This can make a difference when the expressions have side
effects.  For example, in the expression

     a & b++

the value of the variable B is incremented even if the variable A is
zero.

   This behavior is necessary for the boolean operators to work as
described for matrix-valued operands.


File: octave.info,  Node: Short-circuit Boolean Operators,  Prev: Element-by-element Boolean Operators,  Up: Boolean Expressions

10.5.2 Short-circuit Boolean Operators
--------------------------------------

Combined with the implicit conversion to scalar values in `if' and
`while' conditions, Octave's element-by-element boolean operators are
often sufficient for performing most logical operations.  However, it
is sometimes desirable to stop evaluating a boolean expression as soon
as the overall truth value can be determined.  Octave's "short-circuit"
boolean operators work this way.

`BOOLEAN1 && BOOLEAN2'
     The expression BOOLEAN1 is evaluated and converted to a scalar
     using the equivalent of the operation `all (all (BOOLEAN1))'.  If
     it is false, the result of the overall expression is 0.  If it is
     true, the expression BOOLEAN2 is evaluated and converted to a
     scalar using the equivalent of the operation `all (all
     (BOOLEAN1))'.  If it is true, the result of the overall expression
     is 1.  Otherwise, the result of the overall expression is 0.

`BOOLEAN1 || BOOLEAN2'
     The expression BOOLEAN1 is evaluated and converted to a scalar
     using the equivalent of the operation `all (all (BOOLEAN1))'.  If
     it is true, the result of the overall expression is 1.  If it is
     false, the expression BOOLEAN2 is evaluated and converted to a
     scalar using the equivalent of the operation `all (all
     (BOOLEAN1))'.  If it is true, the result of the overall expression
     is 1.  Otherwise, the result of the overall expression is 0.

   The fact that both operands may not be evaluated before determining
the overall truth value of the expression can be important.  For
example, in the expression

     a && b++

the value of the variable B is only incremented if the variable A is
nonzero.

   This can be used to write somewhat more concise code.  For example,
it is possible write

     function f (a, b, c)
       if (nargin > 2 && isstr (c))
         ...

instead of having to use two `if' statements to avoid attempting to
evaluate an argument that doesn't exist.  For example, without the
short-circuit feature, it would be necessary to write

     function f (a, b, c)
       if (nargin > 2)
         if (isstr (c))
           ...

   Writing

     function f (a, b, c)
       if (nargin > 2 & isstr (c))
         ...

would result in an error if `f' were called with one or two arguments
because Octave would be forced to try to evaluate both of the operands
for the operator `&'.


File: octave.info,  Node: Assignment Ops,  Next: Increment Ops,  Prev: Boolean Expressions,  Up: Expressions

10.6 Assignment Expressions
===========================

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

     z = 1

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

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

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

(This also illustrates concatenation of strings.)

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

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

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

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

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

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

     a(:, 2) = 5

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

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

     A (3, :) = []

deletes the third row of A, and the assignment

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

deletes the first, second, and fifth columns.

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

     x = y = z = 0

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

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

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

that is exactly equivalent to

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

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

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

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

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

is equivalent to

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

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

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


File: octave.info,  Node: Increment Ops,  Next: Operator Precedence,  Prev: Assignment Ops,  Up: Expressions

10.7 Increment Operators
========================

_Increment operators_ increase or decrease the value of a variable by
1.  The operator to increment a variable is written as `++'.  It may be
used to increment a variable either before or after taking its value.

   For example, to pre-increment the variable X, you would write `++X'.
This would add one to X and then return the new value of X as the
result of the expression.  It is exactly the same as the expression `X
= X + 1'.

   To post-increment a variable X, you would write `X++'.  This adds
one to the variable X, but returns the value that X had prior to
incrementing it.  For example, if X is equal to 2, the result of the
expression `X++' is 2, and the new value of X is 3.

   For matrix and vector arguments, the increment and decrement
operators work on each element of the operand.

   Here is a list of all the increment and decrement expressions.

`++X'
     This expression increments the variable X.  The value of the
     expression is the _new_ value of X.  It is equivalent to the
     expression `X = X + 1'.

`--X'
     This expression decrements the variable X.  The value of the
     expression is the _new_ value of X.  It is equivalent to the
     expression `X = X - 1'.

`X++'
     This expression causes the variable X to be incremented.  The
     value of the expression is the _old_ value of X.

`X--'
     This expression causes the variable X to be decremented.  The
     value of the expression is the _old_ value of X.

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


File: octave.info,  Node: Operator Precedence,  Prev: Increment Ops,  Up: Expressions

10.8 Operator Precedence
========================

"Operator precedence" determines how operators are grouped, when
different operators appear close by in one expression.  For example,
`*' has higher precedence than `+'.  Thus, the expression `a + b * c'
means to multiply `b' and `c', and then add `a' to the product (i.e.,
`a + (b * c)').

   You can overrule the precedence of the operators by using
parentheses.  You can think of the precedence rules as saying where the
parentheses are assumed if you do not write parentheses yourself.  In
fact, it is wise to use parentheses whenever you have an unusual
combination of operators, because other people who read the program may
not remember what the precedence is in this case.  You might forget as
well, and then you too could make a mistake.  Explicit parentheses will
help prevent any such mistake.

   When operators of equal precedence are used together, the leftmost
operator groups first, except for the assignment and exponentiation
operators, which group in the opposite order.  Thus, the expression `a
- b + c' groups as `(a - b) + c', but the expression `a = b = c' groups
as `a = (b = c)'.

   The precedence of prefix unary operators is important when another
operator follows the operand.  For example, `-x^2' means `-(x^2)',
because `-' has lower precedence than `^'.

   Here is a table of the operators in Octave, in order of increasing
precedence.

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

`assignment'
     `='.  This operator groups right to left.

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

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

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

`colon'
     `:'.

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

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

`transpose'
     `'', `.''

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

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


File: octave.info,  Node: Evaluation,  Next: Statements,  Prev: Expressions,  Up: Top

11 Evaluation
*************

Normally, you evaluate expressions simply by typing them at the Octave
prompt, or by asking Octave to interpret commands that you have saved in
a file.

   Sometimes, you may find it necessary to evaluate an expression that
has been computed and stored in a string, or use a string as the name
of a function to call.  The `eval' and `feval' functions allow you to
do just that, and are necessary in order to evaluate commands that are
not known until run time, or to write functions that will need to call
user-supplied functions.

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

 -- Built-in Function:  feval (NAME, ...)
     Evaluate the function named NAME.  Any arguments after the first
     are passed on to the named function.  For example,

          feval ("acos", -1)
               => 3.1416

     calls the function `acos' with the argument `-1'.

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

   Here is a simple-minded function using `feval' that finds the root
of a user-supplied function of one variable using Newton's method.

     function result = newtroot (fname, x)

     # usage: newtroot (fname, x)
     #
     #   fname : a string naming a function f(x).
     #   x     : initial guess

       delta = tol = sqrt (eps);
       maxit = 200;
       fx = feval (fname, x);
       for i = 1:maxit
         if (abs (fx) < tol)
           result = x;
           return;
         else
           fx_new = feval (fname, x + delta);
           deriv = (fx_new - fx) / delta;
           x = x - fx / deriv;
           fx = fx_new;
         endif
       endfor

       result = x;

     endfunction

   Note that this is only meant to be an example of calling
user-supplied functions and should not be taken too seriously.  In
addition to using a more robust algorithm, any serious code would check
the number and type of all the arguments, ensure that the supplied
function really was a function, etc.  See *Note Predicates for Numeric
Objects::, for example, for a list of predicates for numeric objects,
and *Note Status of Variables::, for a description of the `exist'
function.


File: octave.info,  Node: Statements,  Next: Functions and Scripts,  Prev: Evaluation,  Up: Top

12 Statements
*************

Statements may be a simple constant expression or a complicated list of
nested loops and conditional statements.

   "Control statements" such as `if', `while', and so on control the
flow of execution in Octave programs.  All the control statements start
with special keywords such as `if' and `while', to distinguish them
from simple expressions.  Many control statements contain other
statements; for example, the `if' statement contains another statement
which may or may not be executed.

   Each control statement has a corresponding "end" statement that
marks the end of the end of the control statement.  For example, the
keyword `endif' marks the end of an `if' statement, and `endwhile'
marks the end of a `while' statement.  You can use the keyword `end'
anywhere a more specific end keyword is expected, but using the more
specific keywords is preferred because if you use them, Octave is able
to provide better diagnostics for mismatched or missing end tokens.

   The list of statements contained between keywords like `if' or
`while' and the corresponding end statement is called the "body" of a
control statement.

* Menu:

* The if Statement::
* The switch Statement::
* The while Statement::
* The do-until Statement::
* The for Statement::
* The break Statement::
* The continue Statement::
* The unwind_protect Statement::
* The try Statement::
* Continuation Lines::


File: octave.info,  Node: The if Statement,  Next: The switch Statement,  Up: Statements

12.1 The `if' Statement
=======================

The `if' statement is Octave's decision-making statement.  There are
three basic forms of an `if' statement.  In its simplest form, it looks
like this:

     if (CONDITION)
       THEN-BODY
     endif

CONDITION is an expression that controls what the rest of the statement
will do.  The THEN-BODY is executed only if CONDITION is true.

   The condition in an `if' statement is considered true if its value
is non-zero, and false if its value is zero.  If the value of the
conditional expression in an `if' statement is a vector or a matrix, it
is considered true only if _all_ of the elements are non-zero.

   The second form of an if statement looks like this:

     if (CONDITION)
       THEN-BODY
     else
       ELSE-BODY
     endif

If CONDITION is true, THEN-BODY is executed; otherwise, ELSE-BODY is
executed.

   Here is an example:

     if (rem (x, 2) == 0)
       printf ("x is even\n");
     else
       printf ("x is odd\n");
     endif

   In this example, if the expression `rem (x, 2) == 0' is true (that
is, the value of `x' is divisible by 2), then the first `printf'
statement is evaluated, otherwise the second `printf' statement is
evaluated.

   The third and most general form of the `if' statement allows
multiple decisions to be combined in a single statement.  It looks like
this:

     if (CONDITION)
       THEN-BODY
     elseif (CONDITION)
       ELSEIF-BODY
     else
       ELSE-BODY
     endif

Any number of `elseif' clauses may appear.  Each condition is tested in
turn, and if one is found to be true, its corresponding BODY is
executed.  If none of the conditions are true and the `else' clause is
present, its body is executed.  Only one `else' clause may appear, and
it must be the last part of the statement.

   In the following example, if the first condition is true (that is,
the value of `x' is divisible by 2), then the first `printf' statement
is executed.  If it is false, then the second condition is tested, and
if it is true (that is, the value of `x' is divisible by 3), then the
second `printf' statement is executed.  Otherwise, the third `printf'
statement is performed.

     if (rem (x, 2) == 0)
       printf ("x is even\n");
     elseif (rem (x, 3) == 0)
       printf ("x is odd and divisible by 3\n");
     else
       printf ("x is odd\n");
     endif

   Note that the `elseif' keyword must not be spelled `else if', as is
allowed in Fortran.  If it is, the space between the `else' and `if'
will tell Octave to treat this as a new `if' statement within another
`if' statement's `else' clause.  For example, if you write

     if (C1)
       BODY-1
     else if (C2)
       BODY-2
     endif

Octave will expect additional input to complete the first `if'
statement.  If you are using Octave interactively, it will continue to
prompt you for additional input.  If Octave is reading this input from a
file, it may complain about missing or mismatched `end' statements, or,
if you have not used the more specific `end' statements (`endif',
`endfor', etc.), it may simply produce incorrect results, without
producing any warning messages.

   It is much easier to see the error if we rewrite the statements above
like this,

     if (C1)
       BODY-1
     else
       if (C2)
         BODY-2
       endif

using the indentation to show how Octave groups the statements.  *Note
Functions and Scripts::.

 -- Built-in Variable: warn_assign_as_truth_value
     If the value of `warn_assign_as_truth_value' is nonzero, a warning
     is issued for statements like

          if (s = t)
            ...

     since such statements are not common, and it is likely that the
     intent was to write

          if (s == t)
            ...

     instead.

     There are times when it is useful to write code that contains
     assignments within the condition of a `while' or `if' statement.
     For example, statements like

          while (c = getc())
            ...

     are common in C programming.

     It is possible to avoid all warnings about such statements by
     setting `warn_assign_as_truth_value' to 0, but that may also let
     real errors like

          if (x = 1)  # intended to test (x == 1)!
            ...

     slip by.

     In such cases, it is possible suppress errors for specific
     statements by writing them with an extra set of parentheses.  For
     example, writing the previous example as

          while ((c = getc()))
            ...

     will prevent the warning from being printed for this statement,
     while allowing Octave to warn about other assignments used in
     conditional contexts.

     The default value of `warn_assign_as_truth_value' is 1.


File: octave.info,  Node: The switch Statement,  Next: The while Statement,  Prev: The if Statement,  Up: Statements

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

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

   The general form of the `switch' statement is

     switch EXPRESSION
       case LABEL
         COMMAND_LIST
       case LABEL
         COMMAND_LIST
       ...

       otherwise
         COMMAND_LIST
     endswitch

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

   * The LABEL may be any expression.

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

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

   * The `otherwise COMMAND_LIST' clause is optional.

   * As with all other specific `end' keywords, `endswitch' may be
     replaced by `end', but you can get better diagnostics if you use
     the specific forms.

   * Cases are exclusive, so they don't `fall through' as do the cases
     in the switch statement of the C language.

   * The COMMAND_LIST elements are not optional.  Making the list
     optional would have meant requiring a separator between the label
     and the command list.  Otherwise, things like

          switch (foo)
            case (1) -2
            ...

     would produce surprising results, as would

          switch (foo)
            case (1)
            case (2)
              doit ();
            ...

     particularly for C programmers.

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

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


File: octave.info,  Node: The while Statement,  Next: The do-until Statement,  Prev: The switch Statement,  Up: Statements

12.3 The `while' Statement
==========================

In programming, a "loop" means a part of a program that is (or at least
can be) executed two or more times in succession.

   The `while' statement is the simplest looping statement in Octave.
It repeatedly executes a statement as long as a condition is true.  As
with the condition in an `if' statement, the condition in a `while'
statement is considered true if its value is non-zero, and false if its
value is zero.  If the value of the conditional expression in a `while'
statement is a vector or a matrix, it is considered true only if _all_
of the elements are non-zero.

   Octave's `while' statement looks like this:

     while (CONDITION)
       BODY
     endwhile

Here BODY is a statement or list of statements that we call the "body"
of the loop, and CONDITION is an expression that controls how long the
loop keeps running.

   The first thing the `while' statement does is test CONDITION.  If
CONDITION is true, it executes the statement BODY.  After BODY has been
executed, CONDITION is tested again, and if it is still true, BODY is
executed again.  This process repeats until CONDITION is no longer
true.  If CONDITION is initially false, the body of the loop is never
executed.

   This example creates a variable `fib' that contains the first ten
elements of the Fibonacci sequence.

     fib = ones (1, 10);
     i = 3;
     while (i <= 10)
       fib (i) = fib (i-1) + fib (i-2);
       i++;
     endwhile

Here the body of the loop contains two statements.

   The loop works like this: first, the value of `i' is set to 3.
Then, the `while' tests whether `i' is less than or equal to 10.  This
is the case when `i' equals 3, so the value of the `i'-th element of
`fib' is set to the sum of the previous two values in the sequence.
Then the `i++' increments the value of `i' and the loop repeats.  The
loop terminates when `i' reaches 11.

   A newline is not required between the condition and the body; but
using one makes the program clearer unless the body is very simple.

   *Note The if Statement::, for a description of the variable
`warn_assign_as_truth_value'.


File: octave.info,  Node: The do-until Statement,  Next: The for Statement,  Prev: The while Statement,  Up: Statements

12.4 The `do-until' Statement
=============================

The `do-until' statement is similar to the `while' statement, except
that it repeatedly executes a statement until a condition becomes true,
and the test of the condition is at the end of the loop, so the body of
the loop is always executed at least once.  As with the condition in an
`if' statement, the condition in a `do-until' statement is considered
true if its value is non-zero, and false if its value is zero.  If the
value of the conditional expression in a `do-until' statement is a
vector or a matrix, it is considered true only if _all_ of the elements
are non-zero.

   Octave's `do-until' statement looks like this:

     do
       BODY
     until (CONDITION)

Here BODY is a statement or list of statements that we call the "body"
of the loop, and CONDITION is an expression that controls how long the
loop keeps running.

   This example creates a variable `fib' that contains the first ten
elements of the Fibonacci sequence.

     fib = ones (1, 10);
     i = 2;
     do
       i++;
       fib (i) = fib (i-1) + fib (i-2);
     until (i == 10)

   A newline is not required between the `do' keyword and the body; but
using one makes the program clearer unless the body is very simple.

   *Note The if Statement::, for a description of the variable
`warn_assign_as_truth_value'.


File: octave.info,  Node: The for Statement,  Next: The break Statement,  Prev: The do-until Statement,  Up: Statements

12.5 The `for' Statement
========================

The `for' statement makes it more convenient to count iterations of a
loop.  The general form of the `for' statement looks like this:

     for VAR = EXPRESSION
       BODY
     endfor

where BODY stands for any statement or list of statements, EXPRESSION
is any valid expression, and VAR may take several forms.  Usually it is
a simple variable name or an indexed variable.  If the value of
EXPRESSION is a structure, VAR may also be a list.  *Note Looping Over
Structure Elements::, below.

   The assignment expression in the `for' statement works a bit
differently than Octave's normal assignment statement.  Instead of
assigning the complete result of the expression, it assigns each column
of the expression to VAR in turn.  If EXPRESSION is a range, a row
vector, or a scalar, the value of VAR will be a scalar each time the
loop body is executed.  If VAR is a column vector or a matrix, VAR will
be a column vector each time the loop body is executed.

   The following example shows another way to create a vector containing
the first ten elements of the Fibonacci sequence, this time using the
`for' statement:

     fib = ones (1, 10);
     for i = 3:10
       fib (i) = fib (i-1) + fib (i-2);
     endfor

This code works by first evaluating the expression `3:10', to produce a
range of values from 3 to 10 inclusive.  Then the variable `i' is
assigned the first element of the range and the body of the loop is
executed once.  When the end of the loop body is reached, the next
value in the range is assigned to the variable `i', and the loop body
is executed again.  This process continues until there are no more
elements to assign.

   Although it is possible to rewrite all `for' loops as `while' loops,
the Octave language has both statements because often a `for' loop is
both less work to type and more natural to think of.  Counting the
number of iterations is very common in loops and it can be easier to
think of this counting as part of looping rather than as something to
do inside the loop.

* Menu:

* Looping Over Structure Elements::


File: octave.info,  Node: Looping Over Structure Elements,  Up: The for Statement

12.5.1 Looping Over Structure Elements
--------------------------------------

A special form of the `for' statement allows you to loop over all the
elements of a structure:

     for [ VAL, KEY ] = EXPRESSION
       BODY
     endfor

In this form of the `for' statement, the value of EXPRESSION must be a
structure.  If it is, KEY and VAL are set to the name of the element
and the corresponding value in turn, until there are no more elements.
For example,

     x.a = 1
     x.b = [1, 2; 3, 4]
     x.c = "string"
     for [val, key] = x
       key
       val
     endfor

          -| key = a
          -| val = 1
          -| key = b
          -| val =
          -|
          -|   1  2
          -|   3  4
          -|
          -| key = c
          -| val = string

   The elements are not accessed in any particular order.  If you need
to cycle through the list in a particular way, you will have to use the
function `struct_elements' and sort the list yourself.

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


File: octave.info,  Node: The break Statement,  Next: The continue Statement,  Prev: The for Statement,  Up: Statements

12.6 The `break' Statement
==========================

The `break' statement jumps out of the innermost `for' or `while' loop
that encloses it.  The `break' statement may only be used within the
body of a loop.  The following example finds the smallest divisor of a
given integer, and also identifies prime numbers:

     num = 103;
     div = 2;
     while (div*div <= num)
       if (rem (num, div) == 0)
         break;
       endif
       div++;
     endwhile
     if (rem (num, div) == 0)
       printf ("Smallest divisor of %d is %d\n", num, div)
     else
       printf ("%d is prime\n", num);
     endif

   When the remainder is zero in the first `while' statement, Octave
immediately "breaks out" of the loop.  This means that Octave proceeds
immediately to the statement following the loop and continues
processing.  (This is very different from the `exit' statement which
stops the entire Octave program.)

   Here is another program equivalent to the previous one.  It
illustrates how the CONDITION of a `while' statement could just as well
be replaced with a `break' inside an `if':

     num = 103;
     div = 2;
     while (1)
       if (rem (num, div) == 0)
         printf ("Smallest divisor of %d is %d\n", num, div);
         break;
       endif
       div++;
       if (div*div > num)
         printf ("%d is prime\n", num);
         break;
       endif
     endwhile


File: octave.info,  Node: The continue Statement,  Next: The unwind_protect Statement,  Prev: The break Statement,  Up: Statements

12.7 The `continue' Statement
=============================

The `continue' statement, like `break', is used only inside `for' or
`while' loops.  It skips over the rest of the loop body, causing the
next cycle around the loop to begin immediately.  Contrast this with
`break', which jumps out of the loop altogether.  Here is an example:

     # print elements of a vector of random
     # integers that are even.

     # first, create a row vector of 10 random
     # integers with values between 0 and 100:

     vec = round (rand (1, 10) * 100);

     # print what we're interested in:

     for x = vec
       if (rem (x, 2) != 0)
         continue;
       endif
       printf ("%d\n", x);
     endfor

   If one of the elements of VEC is an odd number, this example skips
the print statement for that element, and continues back to the first
statement in the loop.

   This is not a practical example of the `continue' statement, but it
should give you a clear understanding of how it works.  Normally, one
would probably write the loop like this:

     for x = vec
       if (rem (x, 2) == 0)
         printf ("%d\n", x);
       endif
     endfor


File: octave.info,  Node: The unwind_protect Statement,  Next: The try Statement,  Prev: The continue Statement,  Up: Statements

12.8 The `unwind_protect' Statement
===================================

Octave supports a limited form of exception handling modelled after the
unwind-protect form of Lisp.

   The general form of an `unwind_protect' block looks like this:

     unwind_protect
       BODY
     unwind_protect_cleanup
       CLEANUP
     end_unwind_protect

Where BODY and CLEANUP are both optional and may contain any Octave
expressions or commands.  The statements in CLEANUP are guaranteed to
be executed regardless of how control exits BODY.

   This is useful to protect temporary changes to global variables from
possible errors.  For example, the following code will always restore
the original value of the built-in variable `warn_fortran_indexing'
even if an error occurs while performing the indexing operation.

     save_warn_fortran_indexing = warn_fortran_indexing;
     unwind_protect
       warn_fortran_indexing = 1;
       elt = a (idx)
     unwind_protect_cleanup
       warn_fortran_indexing = save_warn_fortran_indexing;
     end_unwind_protect

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


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

12.9 The `try' Statement
========================

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

   The general form of a `try' block looks like this:

     try
       BODY
     catch
       CLEANUP
     end_try_catch

   Where BODY and CLEANUP are both optional and may contain any Octave
expressions or commands.  The statements in CLEANUP are only executed
if an error occurs in BODY.

   No warnings or error messages are printed while BODY is executing.
If an error does occur during the execution of BODY, CLEANUP can use
the function `lasterr' to access the text of the message that would
have been printed.  This is the same as `eval (TRY, CATCH)' but it is
more efficient since the commands do not need to be parsed each time
the TRY and CATCH statements are evaluated.  *Note Error Handling::,
for more information about the `lasterr' function.

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


File: octave.info,  Node: Continuation Lines,  Prev: The try Statement,  Up: Statements

12.10 Continuation Lines
========================

In the Octave language, most statements end with a newline character and
you must tell Octave to ignore the newline character in order to
continue a statement from one line to the next.  Lines that end with the
characters `...' or `\' are joined with the following line before they
are divided into tokens by Octave's parser.  For example, the lines

     x = long_variable_name ...
         + longer_variable_name \
         - 42

form a single statement.  The backslash character on the second line
above is interpreted a continuation character, _not_ as a division
operator.

   For continuation lines that do not occur inside string constants,
whitespace and comments may appear between the continuation marker and
the newline character.  For example, the statement

     x = long_variable_name ...     # comment one
         + longer_variable_name \   # comment two
         - 42                       # last comment

is equivalent to the one shown above.  Inside string constants, the
continuation marker must appear at the end of the line just before the
newline character.

   Input that occurs inside parentheses can be continued to the next
line without having to use a continuation marker.  For example, it is
possible to write statements like

     if (fine_dining_destination == on_a_boat
         || fine_dining_destination == on_a_train)
       seuss (i, will, not, eat, them, sam, i, am, i,
              will, not, eat, green, eggs, and, ham);
     endif

without having to add to the clutter with continuation markers.


File: octave.info,  Node: Functions and Scripts,  Next: Error Handling,  Prev: Statements,  Up: Top

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

Complicated Octave programs can often be simplified by defining
functions.  Functions can be defined directly on the command line during
interactive Octave sessions, or in external files, and can be called
just like built-in functions.

* Menu:

* Defining Functions::
* Multiple Return Values::
* Variable-length Argument Lists::
* Variable-length Return Lists::
* Returning From a Function::
* Function Files::
* Script Files::
* Dynamically Linked Functions::
* Function Handles and Inline::
* Organization of Functions::


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

13.1 Defining Functions
=======================

In its simplest form, the definition of a function named NAME looks
like this:

     function NAME
       BODY
     endfunction

A valid function name is like a valid variable name: a sequence of
letters, digits and underscores, not starting with a digit.  Functions
share the same pool of names as variables.

   The function BODY consists of Octave statements.  It is the most
important part of the definition, because it says what the function
should actually _do_.

   For example, here is a function that, when executed, will ring the
bell on your terminal (assuming that it is possible to do so):

     function wakeup
       printf ("\a");
     endfunction

   The `printf' statement (*note Input and Output::) simply tells
Octave to print the string `"\a"'.  The special character `\a' stands
for the alert character (ASCII 7).  *Note Strings::.

   Once this function is defined, you can ask Octave to evaluate it by
typing the name of the function.

   Normally, you will want to pass some information to the functions you
define.  The syntax for passing parameters to a function in Octave is

     function NAME (ARG-LIST)
       BODY
     endfunction

where ARG-LIST is a comma-separated list of the function's arguments.
When the function is called, the argument names are used to hold the
argument values given in the call.  The list of arguments may be empty,
in which case this form is equivalent to the one shown above.

   To print a message along with ringing the bell, you might modify the
`beep' to look like this:

     function wakeup (message)
       printf ("\a%s\n", message);
     endfunction

   Calling this function using a statement like this

     wakeup ("Rise and shine!");

will cause Octave to ring your terminal's bell and print the message
`Rise and shine!', followed by a newline character (the `\n' in the
first argument to the `printf' statement).

   In most cases, you will also want to get some information back from
the functions you define.  Here is the syntax for writing a function
that returns a single value:

     function RET-VAR = NAME (ARG-LIST)
       BODY
     endfunction

The symbol RET-VAR is the name of the variable that will hold the value
to be returned by the function.  This variable must be defined before
the end of the function body in order for the function to return a
value.

   Variables used in the body of a function are local to the function.
Variables named in ARG-LIST and RET-VAR are also local to the function.
*Note Global Variables::, for information about how to access global
variables inside a function.

   For example, here is a function that computes the average of the
elements of a vector:

     function retval = avg (v)
       retval = sum (v) / length (v);
     endfunction

   If we had written `avg' like this instead,

     function retval = avg (v)
       if (isvector (v))
         retval = sum (v) / length (v);
       endif
     endfunction

and then called the function with a matrix instead of a vector as the
argument, Octave would have printed an error message like this:

     error: `retval' undefined near line 1 column 10
     error: evaluating index expression near line 7, column 1

because the body of the `if' statement was never executed, and `retval'
was never defined.  To prevent obscure errors like this, it is a good
idea to always make sure that the return variables will always have
values, and to produce meaningful error messages when problems are
encountered.  For example, `avg' could have been written like this:

     function retval = avg (v)
       retval = 0;
       if (isvector (v))
         retval = sum (v) / length (v);
       else
         error ("avg: expecting vector argument");
       endif
     endfunction

   There is still one additional problem with this function.  What if
it is called without an argument?  Without additional error checking,
Octave will probably print an error message that won't really help you
track down the source of the error.  To allow you to catch errors like
this, Octave provides each function with an automatic variable called
`nargin'.  Each time a function is called, `nargin' is automatically
initialized to the number of arguments that have actually been passed
to the function.  For example, we might rewrite the `avg' function like
this:

     function retval = avg (v)
       retval = 0;
       if (nargin != 1)
         usage ("avg (vector)");
       endif
       if (isvector (v))
         retval = sum (v) / length (v);
       else
         error ("avg: expecting vector argument");
       endif
     endfunction

   Although Octave does not automatically report an error if you call a
function with more arguments than expected, doing so probably indicates
that something is wrong.  Octave also does not automatically report an
error if a function is called with too few arguments, but any attempt to
use a variable that has not been given a value will result in an error.
To avoid such problems and to provide useful messages, we check for both
possibilities and issue our own error message.

 -- Built-in Function:  nargin ()
 -- Built-in Function:  nargin (FCN_NAME)
     Within a function, return the number of arguments passed to the
     function.  At the top level, return the number of command line
     arguments passed to Octave.  If called with the optional argument
     FCN_NAME, return the maximum number of arguments the named
     function can accept, or -1 if the function accepts a variable
     number of arguments.

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

     For example, if the function

          function f ()
            2 + 2
          endfunction

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

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


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

13.2 Multiple Return Values
===========================

Unlike many other computer languages, Octave allows you to define
functions that return more than one value.  The syntax for defining
functions that return multiple values is

     function [RET-LIST] = NAME (ARG-LIST)
       BODY
     endfunction

where NAME, ARG-LIST, and BODY have the same meaning as before, and
RET-LIST is a comma-separated list of variable names that will hold the
values returned from the function.  The list of return values must have
at least one element.  If RET-LIST has only one element, this form of
the `function' statement is equivalent to the form described in the
previous section.

   Here is an example of a function that returns two values, the maximum
element of a vector and the index of its first occurrence in the vector.

     function [max, idx] = vmax (v)
       idx = 1;
       max = v (idx);
       for i = 2:length (v)
         if (v (i) > max)
           max = v (i);
           idx = i;
         endif
       endfor
     endfunction

   In this particular case, the two values could have been returned as
elements of a single array, but that is not always possible or
convenient.  The values to be returned may not have compatible
dimensions, and it is often desirable to give the individual return
values distinct names.

   In addition to setting `nargin' each time a function is called,
Octave also automatically initializes `nargout' to the number of values
that are expected to be returned.  This allows you to write functions
that behave differently depending on the number of values that the user
of the function has requested.  The implicit assignment to the built-in
variable `ans' does not figure in the count of output arguments, so the
value of `nargout' may be zero.

   The `svd' and `lu' functions are examples of built-in functions that
behave differently depending on the value of `nargout'.

   It is possible to write functions that only set some return values.
For example, calling the function

     function [x, y, z] = f ()
       x = 1;
       z = 2;
     endfunction

as

     [a, b, c] = f ()

produces:

     a = 1

     b = [](0x0)

     c = 2

along with a warning if the value of the built-in variable
`warn_undefined_return_values' is nonzero.

 -- Built-in Function:  nargout ()
 -- Built-in Function:  nargout (FCN_NAME)
     Within a function, return the number of values the caller expects
     to receive.  If called with the optional argument FCN_NAME, return
     the maximum number of values the named function can produce, or -1
     if the function can produce a variable number of values.

     For example,

          f ()

     will cause `nargout' to return 0 inside the function `f' and

          [s, t] = f ()

     will cause `nargout' to return 2 inside the function `f'.

     At the top level, `nargout' is undefined.

 -- Built-in Variable: warn_undefined_return_values
     If the value of `warn_undefined_return_values' is nonzero, print a
     warning if a function does not define all the values in the return
     list which are expected.  The default value is 1.

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

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


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

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


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

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


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

13.5 Returning From a Function
==============================

The body of a user-defined function can contain a `return' statement.
This statement returns control to the rest of the Octave program.  It
looks like this:

     return

   Unlike the `return' statement in C, Octave's `return' statement
cannot be used to return a value from a function.  Instead, you must
assign values to the list of return variables that are part of the
`function' statement.  The `return' statement simply makes it easier to
exit a function from a deeply nested loop or conditional statement.

   Here is an example of a function that checks to see if any elements
of a vector are nonzero.

     function retval = any_nonzero (v)
       retval = 0;
       for i = 1:length (v)
         if (v (i) != 0)
           retval = 1;
           return;
         endif
       endfor
       printf ("no nonzero elements found\n");
     endfunction

   Note that this function could not have been written using the
`break' statement to exit the loop once a nonzero value is found
without adding extra logic to avoid printing the message if the vector
does contain a nonzero element.

 -- Keyword: return
     When Octave encounters the keyword `return' inside a function or
     script, it returns control to the caller immediately. At the top
     level, the return statement is ignored.  A `return' statement is
     assumed at the end of every function definition.


File: octave.info,  Node: Function Files,  Next: Script Files,  Prev: Returning From a Function,  Up: Functions and Scripts

13.6 Function Files
===================

Except for simple one-shot programs, it is not practical to have to
define all the functions you need each time you need them.  Instead, you
will normally want to save them in a file so that you can easily edit
them, and save them for use at a later time.

   Octave does not require you to load function definitions from files
before using them.  You simply need to put the function definitions in a
place where Octave can find them.

   When Octave encounters an identifier that is undefined, it first
looks for variables or functions that are already compiled and currently
listed in its symbol table.  If it fails to find a definition there, it
searches the list of directories specified by the built-in variable
`LOADPATH' for files ending in `.m' that have the same base name as the
undefined identifier.(1)  Once Octave finds a file with a name that
matches, the contents of the file are read.  If it defines a _single_
function, it is compiled and executed.  *Note Script Files::, for more
information about how you can define more than one function in a single
file.

   When Octave defines a function from a function file, it saves the
full name of the file it read and the time stamp on the file.  After
that, it checks the time stamp on the file every time it needs the
function.  If the time stamp indicates that the file has changed since
the last time it was read, Octave reads it again.

   Checking the time stamp allows you to edit the definition of a
function while Octave is running, and automatically use the new function
definition without having to restart your Octave session.  Checking the
time stamp every time a function is used is rather inefficient, but it
has to be done to ensure that the correct function definition is used.

   To avoid degrading performance unnecessarily by checking the time
stamps on functions that are not likely to change, Octave assumes that
function files in the directory tree
`OCTAVE-HOME/share/octave/VERSION/m' will not change, so it doesn't
have to check their time stamps every time the functions defined in
those files are used.  This is normally a very good assumption and
provides a significant improvement in performance for the function
files that are distributed with Octave.

   If you know that your own function files will not change while you
are running Octave, you can improve performance by setting the variable
`ignore_function_time_stamp' to `"all"', so that Octave will ignore the
time stamps for all function files.  Setting it to `"system"' gives the
default behavior.  If you set it to anything else, Octave will check
the time stamps on all function files.

 -- Built-in Variable: DEFAULT_LOADPATH
     A colon separated list of directories in which to search for
     function files.  The value of this variable is automatically
     substituted for leading, trailing, or doubled colons that appear
     in the built-in variable `LOADPATH'.

 -- Built-in Variable: LOADPATH
     A colon separated list of directories in which to search for
     function files.  *Note Functions and Scripts::.  The value of
     `LOADPATH' overrides the environment variable `OCTAVE_PATH'.
     *Note Installation::.

     `LOADPATH' is now handled in the same way as TeX handles
     `TEXINPUTS'.  Leading, trailing, or doubled colons that appear in
     `LOADPATH' are replaced by the value of `DEFAULT_LOADPATH'.  The
     default value of `LOADPATH' is `":"', which tells Octave to search
     in the directories specified by `DEFAULT_LOADPATH'.

     In addition, if any path element ends in `//', that directory and
     all subdirectories it contains are searched recursively for
     function files.  This can result in a slight delay as Octave
     caches the lists of files found in the `LOADPATH' the first time
     Octave searches for a function.  After that, searching is usually
     much faster because Octave normally only needs to search its
     internal cache for files.

     To improve performance of recursive directory searching, it is
     best for each directory that is to be searched recursively to
     contain _either_ additional subdirectories _or_ function files, but
     not a mixture of both.

     *Note Organization of Functions::, for a description of the
     function file directories that are distributed with Octave.

 -- Built-in Function:  rehash ()
     Reinitialize Octave's `LOADPATH' directory cache.

 -- Built-in Function:  file_in_loadpath (FILE)
 -- Built-in Function:  file_in_loadpath (FILE, "all")
     Return the absolute name name of FILE if it can be found in the
     list of directories specified by `LOADPATH'.  If no file is found,
     return an empty matrix.

     If the first argument is a cell array of of strings, search each
     directory of the loadpath for element of the cell array and return
     the first that matches.

     If the second optional argument `"all"' is supplied, return a cell
     array containing the list of all files that have the same name in
     the path.  If no files are found, return an empty cell array.

 -- Built-in Variable: ignore_function_time_stamp
     This variable can be used to prevent Octave from making the system
     call `stat' each time it looks up functions defined in function
     files.  If `ignore_function_time_stamp' to `"system"', Octave will
     not automatically recompile function files in subdirectories of
     `OCTAVE-HOME/lib/VERSION' if they have changed since they were
     last compiled, but will recompile other function files in the
     `LOADPATH' if they change.  If set to `"all"', Octave will not
     recompile any function files unless their definitions are removed
     with `clear'.  For any other value of `ignore_function_time_stamp',
     Octave will always check to see if functions defined in function
     files need to recompiled.  The default value of
     `ignore_function_time_stamp' is `"system"'.

 -- Built-in Variable: warn_function_name_clash
     If the value of `warn_function_name_clash' is nonzero, 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.)  If the
     value is 0, the warning is omitted.  The default value is 1.

 -- Built-in Variable: warn_future_time_stamp
     If the value of this variable is nonzero, Octave will print a
     warning if it finds a function file with a time stamp that is in
     the future.

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

   (1) The `.m' suffix was chosen for compatibility with MATLAB.


File: octave.info,  Node: Script Files,  Next: Dynamically Linked Functions,  Prev: Function Files,  Up: Functions and Scripts

13.7 Script Files
=================

A script file is a file containing (almost) any sequence of Octave
commands.  It is read and evaluated just as if you had typed each
command at the Octave prompt, and provides a convenient way to perform a
sequence of commands that do not logically belong inside a function.

   Unlike a function file, a script file must _not_ begin with the
keyword `function'.  If it does, Octave will assume that it is a
function file, and that it defines a single function that should be
evaluated as soon as it is defined.

   A script file also differs from a function file in that the variables
named in a script file are not local variables, but are in the same
scope as the other variables that are visible on the command line.

   Even though a script file may not begin with the `function' keyword,
it is possible to define more than one function in a single script file
and load (but not execute) all of them at once.  To do this, the first
token in the file (ignoring comments and other white space) must be
something other than `function'.  If you have no other statements to
evaluate, you can use a statement that has no effect, like this:

     # Prevent Octave from thinking that this
     # is a function file:

     1;

     # Define function one:

     function one ()
       ...

   To have Octave read and compile these functions into an internal
form, you need to make sure that the file is in Octave's `LOADPATH',
then simply type the base name of the file that contains the commands.
(Octave uses the same rules to search for script files as it does to
search for function files.)

   If the first token in a file (ignoring comments) is `function',
Octave will compile the function and try to execute it, printing a
message warning about any non-whitespace characters that appear after
the function definition.

   Note that Octave does not try to look up the definition of any
identifier until it needs to evaluate it.  This means that Octave will
compile the following statements if they appear in a script file, or
are typed at the command line,

     # not a function file:
     1;
     function foo ()
       do_something ();
     endfunction
     function do_something ()
       do_something_else ();
     endfunction

even though the function `do_something' is not defined before it is
referenced in the function `foo'.  This is not an error because Octave
does not need to resolve all symbols that are referenced by a function
until the function is actually evaluated.

   Since Octave doesn't look for definitions until they are needed, the
following code will always print `bar = 3' whether it is typed directly
on the command line, read from a script file, or is part of a function
body, even if there is a function or script file called `bar.m' in
Octave's `LOADPATH'.

     eval ("bar = 3");
     bar

   Code like this appearing within a function body could fool Octave if
definitions were resolved as the function was being compiled.  It would
be virtually impossible to make Octave clever enough to evaluate this
code in a consistent fashion.  The parser would have to be able to
perform the call to `eval' at compile time, and that would be
impossible unless all the references in the string to be evaluated could
also be resolved, and requiring that would be too restrictive (the
string might come from user input, or depend on things that are not
known until the function is evaluated).

   Although Octave normally executes commands from script files that
have the name `FILE.m', you can use the function `source' to execute
commands from any file.

 -- Built-in Function:  source (FILE)
     Parse and execute the contents of FILE.  This is equivalent to
     executing commands from a script file, but without requiring the
     file to be named `FILE.m'.


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

13.8 Dynamically Linked Functions
=================================

On some systems, Octave can dynamically load and execute functions
written in C++.  Octave can only directly call functions written in C++,
but you can also load functions written in other languages by calling
them from a simple wrapper function written in C++.

   Here is an example of how to write a C++ function that Octave can
load, with commentary.  The source for this function is included in the
source distributions of Octave, in the file `examples/oregonator.cc'.
It defines the same set of differential equations that are used in the
example problem of *Note Ordinary Differential Equations::.  By running
that example and this one, we can compare the execution times to see
what sort of increase in speed you can expect by using dynamically
linked functions.

   The function defined in `oregonator.cc' contains just 8 statements,
and is not much different than the code defined in the corresponding
M-file (also distributed with Octave in the file
`examples/oregonator.m').

   Here is the complete text of `oregonator.cc':

   just

     #include <octave/oct.h>

     DEFUN_DLD (oregonator, args, ,
       "The `oregonator'.")
     {
       ColumnVector dx (3);

       ColumnVector x (args(0).vector_value ());

       dx(0) = 77.27 * (x(1) - x(0)*x(1) + x(0)
                        - 8.375e-06*pow (x(0), 2));

       dx(1) = (x(2) - x(0)*x(1) - x(1)) / 77.27;

       dx(2) = 0.161*(x(0) - x(2));

       return octave_value (dx);
     }

   The first line of the file,

     #include <octave/oct.h>

includes declarations for all of Octave's internal functions that you
will need.  If you need other functions from the standard C++ or C
libraries, you can include the necessary headers here.

   The next two lines
     DEFUN_DLD (oregonator, args, ,
       "The `oregonator'.")

declares the function.  The macro `DEFUN_DLD' and the macros that it
depends on are defined in the files `defun-dld.h', `defun.h', and
`defun-int.h' (these files are included in the header file
`octave/oct.h').

   Note that the third parameter to `DEFUN_DLD' (`nargout') is not
used, so it is omitted from the list of arguments in order to avoid the
warning from gcc about an unused function parameter.

   The next line,

     ColumnVector dx (3);

simply declares an object to store the right hand sides of the
differential equation, and the statement

     ColumnVector x (args(0).vector_value ());

extracts a vector from the first input argument.  The `vector_value'
method is used so that the user of the function can pass either a row
or column vector.  The `ColumnVector' constructor is needed because the
ODE class requires a column vector.  The variable `args' is passed to
functions defined with `DEFUN_DLD' as an `octave_value_list' object,
which includes methods for getting the length of the list and
extracting individual elements.

   In this example, we don't check for errors, but that is not
difficult.  All of the Octave's built-in functions do some form of
checking on their arguments, so you can check the source code for those
functions for examples of various strategies for verifying that the
correct number and types of arguments have been supplied.

   The next statements

     dx(0) = 77.27 * (x(1) - x(0)*x(1) + x(0)
                      - 8.375e-06*pow (x(0), 2));

     dx(1) = (x(2) - x(0)*x(1) - x(1)) / 77.27;

     dx(2) = 0.161*(x(0) - x(2));

define the right-hand side of the differential equation.  Finally, we
can return `dx':

     return octave_value (dx);

The actual return type is `octave_value_list', but it is only necessary
to convert the return type to an `octave_value' because there is a
default constructor that can automatically create an object of that
type from an `octave_value' object, so we can just use that instead.

   To use this file, your version of Octave must support dynamic
linking.  To find out if it does, type the command `octave_config_info
("dld")' at the Octave prompt.  Support for dynamic linking is included
if this command returns 1.

   To compile the example file, type the command `mkoctfile
oregonator.cc' at the shell prompt.  The script `mkoctfile' should have
been installed along with Octave.  Running it will create a file called
`oregonator.oct' that can be loaded by Octave.  To test the
`oregonator.oct' file, start Octave and type the command

     oregonator ([1, 2, 3], 0)

at the Octave prompt.  Octave should respond by printing

     ans =

        77.269353
        -0.012942
        -0.322000

   You can now use the `oregonator.oct' file just as you would the
`oregonator.m' file to solve the set of differential equations.

   On a 133 MHz Pentium running Linux, Octave can solve the problem
shown in *Note Ordinary Differential Equations::, in about 1.4 seconds
using the dynamically linked function, compared to about 19 seconds
using the M-file.  Similar decreases in execution time can be expected
for other functions, particularly those that rely on functions like
`lsode' that require user-supplied functions.

   Just as for M-files, Octave will automatically reload a dynamically
linked function when the file that defines it is more recent than the
last time that the function was loaded.  If more than one function is
defined in a single `.oct' file, reloading the file may force other
functions to be cleared and reloaded.  If all the functions loaded from
a given `.oct' file are cleared, Octave will automatically unload the
`.oct' file.

 -- Built-in Variable: warn_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 `warn_reload_forces_clear', Octave will warn you
     when this happens, and print a list of the additional functions
     that it is forced to clear.

 -- Built-in Variable: variables_can_hide_functions
     If the value of this variable is nonzero, assignments to variables
     may hide previously defined functions of the same name.  A
     negative value will cause Octave to print a warning, but allow the
     operation.

   Additional examples for writing dynamically linked functions are
available in the files in the `src' directory of the Octave
distribution.  Currently, this includes the files

     balance.cc   fft2.cc      inv.cc       qzval.cc
     chol.cc      filter.cc    log.cc       schur.cc
     colloc.cc    find.cc      lsode.cc     sort.cc
     dassl.cc     fsolve.cc    lu.cc        svd.cc
     det.cc       givens.cc    minmax.cc    syl.cc
     eig.cc       hess.cc      pinv.cc
     expm.cc      ifft.cc      qr.cc
     fft.cc       ifft2.cc     quad.cc

These files use the macro `DEFUN_DLD_BUILTIN' instead of `DEFUN_DLD'.
The difference between these two macros is just that
`DEFUN_DLD_BUILTIN' can define a built-in function that is not
dynamically loaded if the operating system does not support dynamic
linking.  To define your own dynamically linked functions you should use
`DEFUN_DLD'.

   There is currently no detailed description of all the functions that
you can call in a built-in function.  For the time being, you will have
to read the source code for Octave.


File: octave.info,  Node: Function Handles and Inline,  Next: Organization of Functions,  Prev: Dynamically Linked Functions,  Up: Functions and Scripts

13.9 Function Handles and Inline
================================

This is a place holder for the description of function handles and
inline functions.

* Menu:

* Function Handles::
* Inline Functions::


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

13.9.1 Function Handles
-----------------------

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

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

 -- Built-in Function:  str2func (FCN_NAME)
     Return a function handle constructed from the string FCN_NAME.


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

13.9.2 Inline Functions
-----------------------

 -- Built-in Function:  inline (STR)
 -- Built-in Function:  inline (STR, ARG1, ...)
 -- Built-in Function:  inline (STR, N)
     Create an inline function from the character string STR.  If
     called with a single argument, the arguments of the generated
     function are extracted from the function itself. The generated
     function arguments will then be in alphabetical order. It should
     be noted that i, and j are ignored as arguments due to the
     ambiguity between their use as a variable or their use as an
     inbuilt constant. All arguments followed by a parentheses are
     considered to be functions.

     If the second and subsequent arguments are character strings, they
     are the names of the arguments of the function.

     If the second argument is an integer N, the arguments are `"x"',
     `"P1"', ..., `"PN"'.

 -- Built-in Function:  argnames (FUN)
     Return a cell array of character strings containing the names of
     the arguments of the inline function FUN.

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

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


File: octave.info,  Node: Organization of Functions,  Prev: Function Handles and Inline,  Up: Functions and Scripts

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

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

`linear-algebra'
     Functions for linear algebra.

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

`plot'
     A set of functions that implement the MATLAB-like plotting
     functions.

`polynomial'
     Functions for manipulating polynomials.

`set'
     Functions for creating and manipulating sets of unique values.

`signal'
     Functions for signal processing applications.

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

`time'
     Functions related to time keeping.


File: octave.info,  Node: Error Handling,  Next: Debugging,  Prev: Functions and Scripts,  Up: Top

14 Error Handling
*****************

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.

 -- Built-in Function:  error (TEMPLATE, ...)
     The `error' function formats the optional arguments under the
     control of the template string TEMPLATE using the same rules as
     the `printf' family of functions (*note Formatted Output::).  The
     resulting message is prefixed by the string `error: ' and printed
     on the `stderr' stream.

     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

 -- Built-in Variable: beep_on_error
     If the value of `beep_on_error' is nonzero, Octave will try to
     ring your terminal's bell before printing an error message.  The
     default value is 0.

 -- Built-in Function:  warning (MSG)
     Print a warning message MSG prefixed by the string `warning: '.
     After printing the warning message, Octave will continue to execute
     commands.  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.

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

 -- Built-in Function:  lasterr ()
 -- Built-in Function:  lasterr (MSG)
     Without any arguments, return the last error message.  With one
     argument, set the last error message to MSG.

 -- Built-in Function:  lastwarn ()
 -- Built-in Function:  lastwarn (MSG)
     Without any arguments, return the last warning message.  With one
     argument, set the last warning message to MSG.

   The following pair of functions are of limited usefulness, and may be
removed from future versions of Octave.

 -- Function File:  perror (NAME, NUM)
     Print the error message for function NAME corresponding to the
     error number NUM.  This function is intended to be used to print
     useful error messages for those functions that return numeric error
     codes.

 -- Function File:  strerror (NAME, NUM)
     Return the text of an error message for function NAME
     corresponding to the error number NUM.  This function is intended
     to be used to print useful error messages for those functions that
     return numeric error codes.


File: octave.info,  Node: Debugging,  Next: Input and Output,  Prev: Error Handling,  Up: Top

15 Debugging
************

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

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


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

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

 -- Loadable Function:  dbwhere ()
     Show where we are in the code

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

 -- Built-in Variable: debug_on_interrupt
     If `debug_on_interrupt' is nonzero, 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.
     The default value is 0.

 -- Built-in Variable: debug_on_warning
     If the value of `debug_on_warning' is nonzero, Octave will try to
     enter the debugger when a warning is encountered.  The default
     value is 0.

 -- Built-in Variable: debug_on_error
     If the value of `debug_on_error' is nonzero, 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).  The default value is 0.


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

16 Input and Output
*******************

There are two distinct classes of input and output functions.  The first
set are modeled after the functions available in MATLAB.  The second
set are modeled after the standard I/O library used by the C
programming language and offer more flexibility and control over the
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 by setting the
variable `PAGER', and you can turn paging off by setting the value of
the variable `page_screen_output' to 0.

 -- Command: more
 -- Command: more on
 -- Command: more off
     Turn output pagination on or off.  Without an argument, `more'
     toggles the current state.

 -- Built-in Variable: PAGER
     The default value is normally `"less"', `"more"', or `"pg"',
     depending on what programs are installed on your system.  *Note
     Installation::.

     When running interactively, Octave sends any output intended for
     your terminal that is more than one screen long to the program
     named by the value of the variable `PAGER'.

 -- Built-in Variable: page_screen_output
     If the value of `page_screen_output' is nonzero, all output
     intended for the screen 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.  The default value is 1.

 -- Built-in Variable: page_output_immediately
     If the value of `page_output_immediately' is nonzero, 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.  The default value is 0.

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

* 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

16.1 Basic Input and Output
===========================

* Menu:

* Terminal Output::
* Terminal Input::
* Simple File I/O::


File: octave.info,  Node: Terminal Output,  Next: Terminal Input,  Up: Basic Input and Output

16.1.1 Terminal Output
----------------------

Since Octave normally prints the value of an expression as soon as it
has been evaluated, the simplest of all I/O functions is a simple
expression.  For example, the following expression will display the
value of pi

     pi
          -| pi = 3.1416

   This works well as long as it is acceptable to have the name of the
variable (or `ans') printed along with the value.  To print the value
of a variable without printing its name, use the function `disp'.

   The `format' command offers some control over the way Octave prints
values with `disp' and through the normal echoing mechanism.

 -- Built-in Variable: ans
     This variable holds 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 of `ans' is 25.

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

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

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

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

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

     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 Variable: print_answer_id_name
     If the value of `print_answer_id_name' is nonzero, variable names
     are printed along with the result.  Otherwise, only the result
     values are printed.  The default value is 1.


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

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

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

   For both `input' and `keyboard', the normal command line history and
editing functions are available at the prompt.

   Octave also has a function that makes it possible to get a single
character from the keyboard without requiring the user to type a
carriage return.

 -- Built-in Function:  kbhit ()
     Read a single keystroke from the keyboard. If called with one
     argument, don't wait for a keypress.  For example,

          x = kbhit ();

     will set X to the next character typed at the keyboard as soon as
     it is typed.

          x = kbhit (1);

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


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

16.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 built-in
variables `default_save_format' and `save_precision'.

   Note that Octave cannot yet save or load structure variables or any
user-defined types.

 -- 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 the built-in
     variable `default_save_format'.

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

          *WARNING: the meaning of this option will change in a future
          version of Octave to be compatible with MATLAB.  To keep the
          meaning of your code the same across this change, use the
          `-text' option instead.*

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

    `-mat'
    `-mat-binary'
          Save the data in MATLAB's 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.

    `-save-builtins'
          Force Octave to save the values of built-in variables too.
          By default, Octave does not save built-in variables.

     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.

   There are three variables that modify the behavior of `save' and
three more that control whether variables are saved when Octave exits
unexpectedly.

 -- Built-in Variable: crash_dumps_octave_core
     If this variable is set to a nonzero value, Octave tries to save
     all current variables the the file "octave-core" if it crashes or
     receives a hangup, terminate or similar signal.  The default value
     is 1.


 -- Built-in Variable: sighup_dumps_octave_core
     If this variable is set to a nonzero value and
     `crash_dumps_octave_core' is also nonzero, Octave tries to save all
     current variables the the file "octave-core" if it receives a
     hangup signal.  The default value is 1.

 -- Built-in Variable: sigterm_dumps_octave_core
     If this variable is set to a nonzero value and
     `crash_dumps_octave_core' is also nonzero, Octave tries to save all
     current variables the the file "octave-core" if it receives a
     terminate signal.  The default value is 1.

 -- Built-in Variable: default_save_format
     This variable specifies the default format for the `save' command.
     It should have one of the following values: `"ascii"', `"binary"',
     `float-binary', or `"mat-binary"'.  The initial default save
     format is Octave's text format.

 -- Built-in Variable: save_precision
     This variable specifies the number of digits to keep when saving
     data in text format.  The default value is 17.

 -- Built-in Variable: save_header_format_string
     This variable specifies the the format string for the comment line
     that is 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>"


 -- Command: load options file v1 v2 ...
     Load the named variables 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 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
          compatiability. Octave now overwrites variables currently in
          memeory with the same name as those found in the file.

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

          *WARNING: the meaning of this option will change in a future
          version of Octave to be compatible with MATLAB.  To keep the
          meaning of your code the same across this change, use the
          `-text' option instead.*

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

    `-mat'
    `-mat-binary'
          Force Octave to assume the file is in MATLAB's version 6
          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
          compatiability.  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.


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

16.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 Variable: stdin
     The standard input stream (file id 0).  When Octave is used
     interactively, this is filtered through the command line editing
     functions.

 -- Built-in Variable: stdout
     The standard output stream (file id 1).  Data written to the
     standard output is normally filtered through the pager.

 -- Built-in Variable: stderr
     The standard error stream (file id 2).  Even if paging is turned
     on, the standard error is not sent to the pager.  It is useful for
     error messages and prompts.

* 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

16.2.1 Opening and Closing Files
--------------------------------

 -- Built-in Function: [FID, MSG] = fopen (NAME, MODE, ARCH)
 -- Built-in Function: FID_LIST = fopen ("all")
 -- Built-in Function: FILE = 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 the name of a
     currently 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 discared.

    `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-returnn on Macintosh).  The default
     if no mode is specified is 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.

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


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

16.2.2 Simple Output
--------------------

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

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

16.2.3 Line-Oriented Input
--------------------------

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

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


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

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

     Return the number of characters printed.

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

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

   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 ("Processing of `%s' is %d%% finished.\nPlease be patient.\n",
             filename, pct);

produces output like

     Processing of `foo.txt' is 37% finished.
     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

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

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

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

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

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

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

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

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

   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

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

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

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

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

16.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.  The are able to automatically swap the byte order of
integer data and convert among ths 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,
     `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'

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


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

16.2.17 Temporary Files
-----------------------

 -- 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 and MSG is an empty string.  Otherwise, FID is -1, NAME
     is empty, and MSG contains a system-dependent error message.

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

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


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

16.2.18 End of File and Errors
------------------------------

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

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

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

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

 -- Built-in Variable: SEEK_SET
 -- Built-in Variable: SEEK_CUR
 -- Built-in Variable: SEEK_END
     These variables may be used as the optional third argument for the
     function `fseek'.

    `SEEK_SET'
          Position file relative to the beginning.

    `SEEK_CUR'
          Position file relative to the current position.

    `SEEK_END'
          used with fseek to 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

17 Plotting
***********

All of Octave's plotting functions use `gnuplot' to handle the actual
graphics. Most types of plots can be generated using the basic plotting
functions, which are patterned after the equivalent functions in
MATLAB. The use of these functions is generally straightforward, and is
the preferred method for generating plots.  However, for users familiar
with `gnuplot', or for some specialized applications where the basic
commands are inadequate, Octave also provides two low-level functions,
`gplot' and `gsplot', that behave almost exactly like the corresponding
`gnuplot' functions `plot' and `splot'. Also note that some advanced
MATLAB features from recent versions are not implemented, such as
handle-graphics and related functions.

* Menu:

* Two-Dimensional Plotting::
* Specialized Two-Dimensional Plots::
* Three-Dimensional Plotting::
* Plot Annotations::
* Multiple Plots on One Page::
* Multiple Plot Windows::
* Low-Level plotting commands::
* Interaction with gnuplot::


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

17.1 Two-Dimensional Plotting
=============================

The MATLAB-style two-dimensional plotting commands are:

 -- Function File:  plot (ARGS)
     This function 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.

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

          plot (X, Y, FMT ...)

     where Y and FMT are optional, and 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 first argument is a vector and the second is a matrix,
          the the vector is plotted versus the columns (or rows) of the
          matrix.  (using whichever combination matches, with columns
          tried first.)

        * If the first argument is a matrix and the second is a vector,
          the the columns (or rows) of the matrix are plotted versus
          the vector.  (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.

     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.

    `@'
          Set points plot style.

    `-@'
          Set linespoints plot style.

    `^'
          Set impulses 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 `"r"', `"g"', `"b"', `"m"', `"c"', or `"w"',
          it is interpreted as the plot color (red, green, blue,
          magenta, cyan, or white).

    `";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 color line styles have the following meanings on terminals that
     support color.

          Number  Gnuplot colors  (lines)points style
            1       red                   *
            2       green                 +
            3       blue                  o
            4       magenta               x
            5       cyan                house
            6       brown            there exists

     The FMT argument can 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, "*")

     This command will plot the data in the variable `b' will be plotted
     with points displayed as `*'.

          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.

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

 -- Built-in Function:  ishold
     Return 1 if the next line will be added to the current plot, or 0
     if the plot device will be cleared before drawing the next line.

 -- Built-in Function:  clearplot
 -- Built-in Function:  clg
     Clear the plot window and any titles or axis labels.  The name
     `clg' is aliased to `clearplot' for compatibility with MATLAB.

     The commands `gplot clear', `gsplot clear', and `replot clear' are
     equivalent to `clearplot'.  (Previously, commands like `gplot
     clear' would evaluate `clear' as an ordinary expression and clear
     all the visible variables.)

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


 -- Built-in Function:  closeplot
     Close stream to the `gnuplot' subprocess.  If you are using X11,
     this will close the plot window.

 -- Built-in Function:  purge_tmp_files
     Delete the temporary files created by the plotting commands.

     Octave creates temporary data files for `gnuplot' and then sends
     commands to `gnuplot' through a pipe.  Octave will delete the
     temporary files on exit, but if you are doing a lot of plotting
     you may want to clean up in the middle of a session.

     A future version of Octave will eliminate the need to use temporary
     files to hold the plot data.

 -- 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 (this
     is not yet implemented for automatic 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.


