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

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

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

* Menu:

* Preface::
* Introduction::                A brief introduction to Octave.
* Getting Started::
* Data Types::
* Numeric Data Types::
* Strings::
* Data Containers::
* Variables::
* Expressions::                 Expressions.
* Evaluation::
* Statements::                  Looping and program flow control.
* Functions and Scripts::
* Errors and Warnings::
* Debugging::
* Input and Output::
* Plotting::
* Matrix Manipulation::
* Arithmetic::
* Linear Algebra::
* Nonlinear Equations::
* Sparse Matrices::
* Numerical Integration::
* Differential Equations::
* Optimization::
* Statistics::
* Financial Functions::
* Sets::
* Polynomial Manipulations::
* Interpolation::
* Geometry::
* Control Theory::
* Signal Processing::
* Image Processing::
* Audio Processing::
* Quaternions::
* System Utilities::
* Packages::
* Dynamically Linked Functions::
* Test and Demo Functions::
* Tips::
* Trouble::                     If you have trouble installing Octave.
* Installation::                How to configure, compile and install Octave.
* Emacs::
* 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 from the Command Line::
* Quitting Octave::
* Getting Help::
* Command Line Editing::
* Errors::
* Executable Octave Programs::
* Comments::

Invoking Octave from the Command Line

* 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::
* Integer Data Types::
* Bit Manipulations::
* Logical Values::
* Predicates for Numeric Objects::

Matrices

* Empty Matrices::

Strings

* Creating Strings::
* Comparing Strings::
* Manipulating Strings::
* String Conversions::
* Character Class Functions::

Data Containers

* Data Structures::
* Cell Arrays::
* Comma Separated Lists::

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::
* Organization of Functions::

Errors and Warnings

* Handling Errors::
* Handling Warnings::

Debugging

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

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

* Plotting Basics::
* Advanced Plotting::

Matrix Manipulation

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

Arithmetic

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

Linear Algebra

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

Sparse Matrices

* Basics::
* Sparse Linear Algebra::
* Iterative Techniques::
* Real Life Example::

Numerical Integration

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

Differential Equations

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

Optimization

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

Statistics

* Descriptive Statistics::
* Basic Statistical Functions::
* Statistical Plots::
* Tests::
* Models::
* Distributions::
* Random Number Generation::

Sets

* Set Operations::

Polynomial Manipulations

* Evaluating Polynomials::
* Finding Roots::
* Products of Polynomials::
* Derivatives and Integrals::
* Polynomial Interpolation::
* Miscellaneous Functions::

Interpolation

* One-dimensional Interpolation::
* Multi-dimensional Interpolation::

Geometry

* Delaunay Triangulation::
* Voronoi Diagrams::
* Convex Hull::
* Interpolation on Scattered Data::

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

Image Processing

* Loading and Saving Images::
* Displaying Images::
* Representing Images::
* Plotting on top of Images::
* Color Conversion::

System Utilities

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

Packages

* Installing and Removing Packages::
* Using Packages::
* Administrating Packages::
* Creating Packages::
* The DESCRIPTION File::
* The INDEX file::
* PKG_ADD and PKG_DEL directives::

Dynamically Linked Functions

* Oct-Files::
* Mex-Files::
* Standalone Programs::

Test and Demo Functions

* Test Functions::
* Demonstration Functions::

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


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.  The
following people have helped write parts of Octave or helped out in
various other ways (listed alphabetically).

Ben Abbott               Andy Adler               Joel Andersson
Muthiah Annamalai        Shai Ayal                Roger Banks
Ben Barrowes             Alexander Barth          David Bateman
Heinz Bauschke           Karl Berry               David Billinghurst
Don Bindner              Jakub Bogusz             Moritz Borgmann
Richard Bovey            Marcus Brinkmann         Remy Bruno
Marco Caliari            Daniel Calvelo           John C. Campbell
Jean-Francois Cardoso    Joao Cardoso             Larrie Carr
David Castelow           Vincent Cautaerts        Clinton Chee
Albert Chin-A-Young      J. D. Cole               Martin Costabel
Michael Creel            Jeff Cunningham          Martin Dalecki
Jorge Barros de Abreu    Philippe Defert          Bill Denney
David M. Doolin          Pascal A. Dupuis         John W. Eaton
Dirk Eddelbuettel        Paul Eggert              Stephen Eglen
Peter Ekberg             Rolf Fabian              Stephen Fegan
Ramon Garcia Fernandez   Torsten Finke            Jose Daniel Munoz Frias
Castor Fu                Eduardo Gallestey        Walter Gautschi
Klaus Gebhardt           Driss Ghaddab            Nicolo Giorgetti
Michael Goffioul         Glenn Golden             Tomislav Goles
Keith Goodman            Etienne Grossmann        Peter Gustafson
Kai Habel                William P. Y.            Benjamin Hall
                         Hadisoeseno              
Kim Hansen               Soren Hauberg            Daniel Heiserer
Yozo Hida                Ryan Hinton              Roman Hodek
A. Scottedward Hodel     Richard Allan Holcombe   Tom Holroyd
David Hoover             Kurt Hornik              Christopher Hulbert
Cyril Humbert            Teemu Ikonen             Alan W. Irwin
Geoff Jacobsen           Mats Jansson             Cai Jianming
Steven G. Johnson        Heikki Junes             Atsushi Kajita
Mohamed Kamoun           Lute Kamstra             Thomas Kasper
Joel Keay                Mumit Khan               Paul Kienzle
Aaron A. King            Arno J. Klaassen         Geoffrey Knauth
Heine Kolltveit          Ken Kouno                Oyvind Kristiansen
Piotr Krzyzanowski       Volker Kuhlmann          Tetsuro Kurita
Miroslaw Kwasniak        Rafael Laboissiere       Kai Labusch
Claude Lacoursiere       Walter Landry            Bill Lash
Dirk Laurie              Maurice LeBrun           Friedrich Leisch
Timo Lindfors            Benjamin Lindner         Ross Lippert
David Livings            Erik de Castro Lopo      Massimo Lorenzin
Emil Lucretiu            Hoxide Ma                James Macnicol
Jens-Uwe Mager           Ricardo Marranita        Orestes Mas
Makoto Matsumoto         Tatsuro Matsuoka         Laurent Mazet
G. D. McBain             Christoph Mayer          Stefan Monnier
Antoine Moreau           Kai P. Mueller           Victor Munoz
Carmen Navarrete         Todd Neal                Al Niessner
Rick Niles               Takuji Nishimura         Eric Norum
Michael O'Brien          Thorsten Ohl             Arno Onken
Luis F. Ortiz            Scott Pakin              Gabriele Pannocchia
Sylvain Pelissier        Per Persson              Primozz Peterlin
Jim Peterson             Danilo Piazzalunga       Nicholas Piper
Hans Ekkehard Plesser    Tom Poage                Orion Poplawski
Ondrej Popp              Jef Poskanzer            Francesco Potorti
James B. Rawlings        Eric S. Raymond          Balint Reczey
Michael Reifenberger     Jason Riedy              Petter Risholm
Matthew W. Roberts       Andrew Ross              Mark van Rossum
Kevin Ruland             Olli Saarela             Toni Saarela
Juhani Saastamoinen      Ben Sapp                 Alois Schloegl
Michel D. Schmid         Nicol N. Schraudolph     Sebastian Schubert
Ludwig Schwardt          Daniel J. Sebald         Dmitri A. Sergatskov
Baylis Shanks            Joseph P. Skudlarek      John Smith
Julius Smith             Shan G. Smith            Joerg Specht
Quentin H. Spencer       Christoph Spiel          Richard Stallman
Russell Standish         Doug Stewart             Thomas Stuart
John Swensen             Ariel Tankus             Georg Thimm
Duncan Temple Lang       Kris Thielemans          Olaf Till
Thomas Treichl           Utkarsh Upadhyay         Stefan van der Walt
Peter Van Wieren         James R. Van Zandt       Gregory Vanuxem
Ivana Varekova           Thomas Walter            Olaf Weber
Thomas Weber             Bob Weigel               Andreas Weingessel
Michael Weitzel          Fook Fah Yap             Michael Zeising
Federico Zenith          Alex Zvoleff             

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

   * The United States Department of Energy, through grant number
     DE-FG02-04ER25635.

   * Ashok Krishnamurthy, David Hudak, Juan Carlos Chaves, and Stanley
     C. Ahalt of the Ohio Supercomputer Center.

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

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

   * John A. Turner, Group Leader, Continuum Dynamics (CCS-2), Los
     Alamos National Laboratory, for registering the `octave.org'
     domain name.

   * James B. Rawlings, Professor, University of Wisconsin-Madison,
     Department of Chemical and Biological 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 can also be downloaded from `http://www.octave.org', where
additional information also is available.


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

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

This manual documents how to install, run, and use 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 3.0.3.

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

1.2.1 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

1.2.2 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

and to form the matrix product `transpose (A) * A', type the command

     octave:6> A' * A

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

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

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

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

     plot (t, x)

If you are using a graphical user interface, Octave will automatically
create a separate window to display the plot.

   To save a plot once it has been displayed on the screen, use the
print command.  For example,

     print -deps foo.eps

will create a file called `foo.eps' that contains a rendering of the
current plot.  The command

     help print

explains more options for the `print' command and provides a list of
additional output file formats.

1.2.6 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, press `Control-p' (usually written `C-p' for short).
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::.

1.2.7 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. An alternative is to search the
documentation using the `lookfor' function. This function is described
in *note Getting Help::.

   Once you know the name of the function you wish to use, you can get
more help on the function 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
category name for functions may include another name that indicates the
way that the function is defined.  These additional tags include

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

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

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 be 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 from the Command Line::
* Quitting Octave::
* Getting Help::
* Command Line Editing::
* Errors::
* Executable Octave Programs::
* Comments::


File: octave.info,  Node: Invoking Octave from the Command Line,  Next: Quitting Octave,  Up: Getting Started

2.1 Invoking Octave from the Command Line
=========================================

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 from the Command Line

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.

`--eval CODE'
     Evaluate CODE and exit when done unless `--persist' is also
     specified.

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

`--image-path PATH'
     Specify the path to search for images.  The value of PATH
     specified on the command line will set the value of `IMAGE_PATH'
     found in the environment.

`--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 use the `info_file'
     function.

`--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 use the
     `info_program' function.

`--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 internal load path
     through one of the path functions.

`--persist'
     Go to interactive mode after `--eval' or reading from a file named
     on the command line.

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

`--traditional'
`--braindead'
     For compatibility with MATLAB, set initial values for
     user-preferences to the following values

          PS1                     = ">> "
          PS2                     = ""
          beep_on_error           = true
          crash_dumps_octave_core = false
          default_save_options    = "-mat-binary"
          fixed_point_format      = true
          history_timestamp_format_string
                                  = "%%-- %D %I:%M %p --%%"
          page_screen_output      = false
          print_empty_dimensions  = false

     and disable the following warnings
          Octave:fopen-file-in-path
          Octave:function-name-clash
          Octave:load-file-in-path

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

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

`FILE'
     Execute commands from FILE.  Exit when done unless `--persist' is
     also specified.

   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 Function:  argv ()
     Return the command line arguments passed to Octave.  For example,
     if you invoked Octave using the command

          octave --no-line-editing --silent

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

     If you write an executable Octave script, `argv' will return 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 Function:  program_name ()
     Return the last component of of the value returned by
     `program_invocation_name'.

     *See also:* program_invocation_name.

 -- Built-in Function: program_invocation_name ()
     Return the name that was typed at the shell prompt to run 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.

     *See also:* program_name.

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

     printf ("%s", program_name ());
     arg_list = argv ();
     for i = 1:nargin
       printf (" %s", arg_list{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 from the Command Line

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

When Octave starts, it looks for commands to execute from the files in
the following list. These files may contain any valid Octave commands,
including function definitions.

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


File: octave.info,  Node: Quitting Octave,  Next: Getting Help,  Prev: Invoking Octave from the Command Line,  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.  The default value is zero.

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

          function bye_bye ()
            disp ("Bye bye");
          endfunction
          atexit ("bye_bye");

     will print the message "Bye bye" when Octave exits.

 -- Built-in Function:  atexit (FCN, FLAG)
     Register or unregister a function to be called when Octave exits,
     depending on FLAG.  If FLAG is true, the function is registered,
     if FLAG is false, it is unregistered.  For example, after
     registering the function `bye_bye' as above,

          atexit ("bye_bye", false);

     will remove the function from the list and Octave will not call
     the function `bye_by' when it exits.

     Note that `atexit' only removes the first occurrence of a function
     from the list, so if a function was placed in the list multiple
     times with `atexit', it must also be removed from the list
     multiple times.


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 `doc'.  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 NAME
     Display the help text for NAME.  If invoked without any arguments,
     `help' prints a list of all the available operators and functions.

     For example, the command `help help' prints a short message
     describing the `help' command.

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

     *See also:* doc, which, lookfor.

 -- Command: doc FUNCTION_NAME
     Display documentation for the function FUNCTION_NAME directly from
     an on-line version of the printed manual, using the GNU Info
     browser.  If invoked without any arguments, the manual is shown
     from the beginning.

     For example, the command `doc rand' 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'.

     *See also:* help.

 -- Command: lookfor STR
 -- Command: lookfor -all STR
 -- Function: [FUN, HELPSTRING] =  lookfor (STR)
 -- Function: [FUN, HELPSTRING] =  lookfor ('-all', STR)
     Search for the string STR in all of the functions found in the
     function search path.  By default `lookfor' searches for STR in
     the first sentence of the help string of each function found. The
     entire help string of each function found in the path can be
     searched if the '-all' argument is supplied. All searches are case
     insensitive.

     Called with no output arguments, `lookfor' prints the list of
     matching functions to the terminal. Otherwise the output arguments
     FUN and HELPSTRING define the matching functions and the first
     sentence of each of their help strings.

     Note that the ability of `lookfor' to correctly identify the first
     sentence of the help of the functions is dependent on the format
     of the functions help. All of the functions in Octave itself will
     correctly find the first sentence, but the same can not be
     guaranteed for other functions. Therefore the use of the '-all'
     argument might be necessary to find related functions that are not
     part of Octave.

     *See also:* help, which.

   The following function can be used to change which programs are used
for displaying the documentation, and where the documentation can be
found.

 -- Built-in Function: VAL = info_file ()
 -- Built-in Function: OLD_VAL = info_file (NEW_VAL)
     Query or set the internal variable that specifies the name 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.

     *See also:* info_program, doc, help, makeinfo_program.

 -- Built-in Function: VAL = info_program ()
 -- Built-in Function: OLD_VAL = info_program (NEW_VAL)
     Query or set the internal variable that specifies the name of the
     info program to run.  The default 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'.

     *See also:* info_file, doc, help, makeinfo_program.

 -- Built-in Function: VAL = makeinfo_program ()
 -- Built-in Function: OLD_VAL = makeinfo_program (NEW_VAL)
     Query or set the internal variable that specifies the name of the
     makeinfo program that Octave runs to format help text containing
     Texinfo markup commands.  The default initial value is
     `"makeinfo"'.

     *See also:* info_file, info_program, doc, help.

 -- Built-in Function: VAL = suppress_verbose_help_message ()
 -- Built-in Function: OLD_VAL = suppress_verbose_help_message (NEW_VAL)
     Query or set the internal variable that controls whether Octave
     will 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 characters 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.

   The function `clc' will allow you to 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'
     Lowercase 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 Function: VAL = completion_append_char ()
 -- Built-in Function: OLD_VAL = completion_append_char (NEW_VAL)
     Query or set the internal character variable that is appended 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.

   Octave also allows you customize the details of how and where the
history is saved.

 -- Built-in Function: VAL = history_file ()
 -- Built-in Function: OLD_VAL = history_file (NEW_VAL)
     Query or set the internal variable that 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'.

     *See also:* history_size, saving_history,
     history_timestamp_format_string.

 -- Built-in Function: VAL = history_size ()
 -- Built-in Function: OLD_VAL = history_size (NEW_VAL)
     Query or set the internal variable that 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'.

     *See also:* history_file, history_timestamp_format, saving_history.

 -- Built-in Function: VAL = saving_history ()
 -- Built-in Function: OLD_VAL = saving_history (NEW_VAL)
     Query or set the internal variable that controls whether commands
     entered on the command line are saved in the history file.

     *See also:* history_file, history_size, history_timestamp_format.

 -- Built-in Function: VAL = history_timestamp_format_string ()
 -- Built-in Function: OLD_VAL = history_timestamp_format_string
          (NEW_VAL)
     Query or set the internal variable that specifies the format string
     for the comment line that is written to the history file when
     Octave exits.  The format string is passed to `strftime'.  The
     default value is

          "# Octave VERSION, %a %b %d %H:%M:%S %Y %Z <USER@HOST>"


     *See also:* strftime, history_file, history_size, saving_history.

 -- Built-in Function: VAL = EDITOR ()
 -- Built-in Function: OLD_VAL = EDITOR (NEW_VAL)
     Query or set the internal variable that specifies 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"'.

     *See also:* edit_history.


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

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

As mentioned earlier Octave uses the GNU readline library for
command-line editing and history features. It is possible to customize
how readline works through a configuration file.

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

     *Note Readline Init File: (readline)Readline Init File, for
     details.


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 Function: VAL = PS1 ()
 -- Built-in Function: OLD_VAL = PS1 (NEW_VAL)
     Query or set the primary prompt string.  When executing
     interactively, Octave displays the primary prompt when it is ready
     to read a command.

     The default value of the primary prompt string 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 double-quoted
     character string.  *Note Strings::.

     *See also:* PS2, PS4.

 -- Built-in Function: VAL = PS2 ()
 -- Built-in Function: OLD_VAL = PS2 (NEW_VAL)
     Query or set the secondary prompt string.  The secondary prompt is
     printed when Octave is expecting additional input to complete a
     command.  For example, if you are typing a for loop that spans
     several lines, Octave will print the secondary prompt at the
     beginning of each line after the first.  The default value of the
     secondary prompt string is `"> "'.

     *See also:* PS1, PS4.

 -- Built-in Function: VAL = PS4 ()
 -- Built-in Function: OLD_VAL = PS4 (NEW_VAL)
     Query or set the character string used to prefix output produced
     when echoing commands when `echo_executing_commands' is enabled.
     The default value is `"+ "'.  *Note Invoking Octave from the
     Command Line::, for a description of `--echo-commands'.

     *See also:* echo_executing_commands, PS1, PS2.


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 Function: VAL = echo_executing_commands ()
 -- Built-in Function: OLD_VAL = echo_executing_commands (NEW_VAL)
     Query or set the internal variable that controls 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).

   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.

   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).  Note that this will only work if `#!'
appears at the very beginning of the file. 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 from the Command Line::.

   Note that some operating systems may place a limit on the number of
characters that are recognized after `#!'.  Also, the various
shells/systems parse differently the arguments appearing in a `#!'
line.  The majority of them group together all the arguments in a string
and pass it to the interpreter as a single argument.  In this case, the
following script:

     #! OCTAVE-INTERPRETER-NAME -q -f # comment

is equivalent to type at the command line:

     octave "-q -f # comment"

which would obviously produce an error message.  Unfortunately, it is
impossible for Octave to know whether it has been called from the
command line or from a `#!' script, so some care is needed when using
the `#!' mechanism.

   Note that when Octave is started from an executable script, the
built-in function `argv' returns a cell array containing the command
line arguments passed to an executable Octave script, not the arguments
passed to the Octave interpreter on the `#!' line of the script.  For
example, the following program will reproduce the command line that is
used to execute script, not `-qf'.

     #! /bin/octave -qf
     printf ("%s", program_name ());
     arg_list = argv ();
     for i = 1:nargin
       printf (" %s", arg_list{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, a
data structure type, and an array that can contain all data types.

   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, a data structure type, and cell
arrays. 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.

   The data type of a variable can be determined and changed through the
use of the following functions.

 -- Built-in Function:  class (EXPR)
     Return the class of the expression EXPR, as a string.

 -- Function File:  isa (X, CLASS)
     Return true if X is a value from the class CLASS.

 -- Function File:  cast (VAL, TYPE)
     Convert VAL to data type TYPE.

     *See also:* int8, uint8, int16, uint16, int32, uint32, int64,
     uint64, double.

 -- Loadable Function:  typecast (X, TYPE)
     Convert from one datatype to another without changing the
     underlying data. The argument TYPE defines the type of the return
     argument and must be one of 'uint8', 'uint16', 'uint32', 'uint64',
     'int8', 'int16', 'int32', 'int64', 'single' or 'double'.

     An example of the use of typecast on a little-endian machine is

          X = uint16 ([1, 65535]);
          typecast (X, 'uint8')
          => [   0,   1, 255, 255]


     *See also:* cast, swapbytes.

 -- Function File:  swapbytes (X)
     Swaps the byte order on values, converting from little endian to
     big endian and visa-versa. For example

          swapbytes (uint16 (1:4))
          => [   256   512   768  1024]


     *See also:* typecast, cast.

* Menu:

* Numeric Objects::
* Missing Data::
* String Objects::
* Data Structure Objects::
* Cell Array 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, complex, and integer
scalars and matrices.  All built-in floating point 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
------------------

It is possible to represent missing data explicitly in Octave using
`NA' (short for "Not Available"). Missing data can only be represented
when data is represented as floating point numbers. In this case
missing data is represented as a special case of the representation of
`NaN'.

 -- Built-in Function:  NA (X)
 -- Built-in Function:  NA (N, M)
 -- Built-in Function:  NA (N, M, K, ...)
 -- Built-in Function:  NA (..., CLASS)
     Return a matrix or N-dimensional array whose elements are all equal
     to the special constant used to designate missing values.

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

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


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,  Next: Cell Array 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: Cell Array Objects,  Prev: Data Structure Objects,  Up: Built-in Data Types

3.1.5 Cell Array Objects
------------------------

A Cell Array in Octave is general array that can hold any number of
different data types.

   *Note Cell Arrays::, 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.

 -- Built-in Function:  ndims (A)
     Returns the number of dimensions of array A.  For any array, the
     result will always be larger than or equal to 2.  Trailing
     singleton dimensions are not counted.

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

     *See also:* size, numel, rows, length, isscalar, isvector, and
     ismatrix.

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

     *See also:* size, numel, columns, length, isscalar, isvector,
     ismatrix.

 -- Built-in Function:  numel (A)
     Returns the number of elements in the object A.

     *See also:* size.

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

     *See also:* numel.

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

 -- Built-in Function:  sizeof (VAL)
     Return the size of VAL in bytes

 -- Built-in Function:  size_equal (A, B, ...)
     Return true if the dimensions of all arguments agree.  Trailing
     singleton dimensions are ignored.

     *See also:* size, numel.

 -- Built-in Function:  squeeze (X)
     Remove singleton dimensions from X and return the result.  Note
     that for compatibility with MATLAB, all objects have a minimum of
     two dimensions and row vectors are left unchanged.


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 by default
numeric constants are represented within Octave in double-precision
floating point format (complex constants are stored as pairs of
double-precision floating point values).  It is however possible to
represent real integers as described in *note Integer Data Types::.
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.

 -- Built-in Function:  double (X)
     Convert X to double precision type.

 -- Function File:  single (VAL)
     Convert the numeric value VAL to single precision.

     *Note*: this function currently returns its argument converted to
     double precision because Octave does not yet have a
     single-precision numeric data type.

 -- Built-in Function:  complex (VAL)
 -- Built-in Function:  complex (RE, IM)
     Convert X to a complex value.

* Menu:

* Matrices::
* Ranges::
* Integer Data Types::
* Bit Manipulations::
* 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 not doing 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.

   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 Function: VAL = output_max_field_width ()
 -- Built-in Function: OLD_VAL = output_max_field_width (NEW_VAL)
     Query or set the internal variable that specifies the maximum width
     of a numeric output field.

     *See also:* format, output_precision.

 -- Built-in Function: VAL = output_precision ()
 -- Built-in Function: OLD_VAL = output_precision (NEW_VAL)
     Query or set the internal variable that specifies the minimum
     number of significant figures to display for numeric output.

     *See also:* format, output_max_field_width.

   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 Function: VAL = split_long_rows ()
 -- Built-in Function: OLD_VAL = split_long_rows (NEW_VAL)
     Query or set the internal variable that controls whether rows of a
     matrix may be split when displayed to a terminal window.  If the
     rows are split, Octave will display the matrix in a series of
     smaller pieces, each of which can fit within the limits of your
     terminal width and 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

   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 Function: VAL = fixed_point_format ()
 -- Built-in Function: OLD_VAL = fixed_point_format (NEW_VAL)
     Query or set the internal variable that controls whether Octave
     will use a scaled format to print matrix values such that the
     largest element may be written with a single leading digit with
     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.

* 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 Function: VAL = print_empty_dimensions ()
 -- Built-in Function: OLD_VAL = print_empty_dimensions (NEW_VAL)
     Query or set the internal variable that controls whether 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.

   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: Integer Data Types,  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: Integer Data Types,  Next: Bit Manipulations,  Prev: Ranges,  Up: Numeric Data Types

4.3 Integer Data Types
======================

Octave supports integer matrices as an alternative to using double
precision. It is possible to use both signed and unsigned integers
represented by 8, 16, 32, or 64 bits. It should be noted that most
computations require floating point data, meaning that integers will
often change type when involved in numeric computations. For this
reason integers are most often used to store data, and not for
calculations.

   In general most integer matrices are created by casting existing
matrices to integers. The following example shows how to cast a matrix
into 32 bit integers.

     float = rand (2, 2)
          => float = 0.37569   0.92982
                     0.11962   0.50876
     integer = int32 (float)
          => integer = 0  1
                       0  1

As can be seen, floating point values are rounded to the nearest integer
when converted.

 -- Built-in Function:  isinteger (X)
     Return true if X is an integer object (int8, uint8, int16, etc.).
     Note that `isinteger (14)' is false because numeric constants in
     are double precision floating point values.

     *See also:* isreal, isnumeric, class, isa.

 -- Built-in Function:  int8 (X)
     Convert X to 8-bit integer type.

 -- Built-in Function:  uint8 (X)
     Convert X to unsigned 8-bit integer type.

 -- Built-in Function:  int16 (X)
     Convert X to 16-bit integer type.

 -- Built-in Function:  uint16 (X)
     Convert X to unsigned 16-bit integer type.

 -- Built-in Function:  int32 (X)
     Convert X to 32-bit integer type.

 -- Built-in Function:  uint32 (X)
     Convert X to unsigned 32-bit integer type.

 -- Built-in Function:  int64 (X)
     Convert X to 64-bit integer type.

 -- Built-in Function:  uint64 (X)
     Convert X to unsigned 64-bit integer type.

 -- Built-in Function:  intmax (TYPE)
     Return the largest integer that can be represented in an integer
     type.  The variable TYPE can be

    `int8'
          signed 8-bit integer.

    `int16'
          signed 16-bit integer.

    `int32'
          signed 32-bit integer.

    `int64'
          signed 64-bit integer.

    `uint8'
          unsigned 8-bit integer.

    `uint16'
          unsigned 16-bit integer.

    `uint32'
          unsigned 32-bit integer.

    `uint64'
          unsigned 64-bit integer.

     The default for TYPE is `uint32'.

     *See also:* intmin, bitmax.

 -- Built-in Function:  intmin (TYPE)
     Return the smallest integer that can be represented in an integer
     type.  The variable TYPE can be

    `int8'
          signed 8-bit integer.

    `int16'
          signed 16-bit integer.

    `int32'
          signed 32-bit integer.

    `int64'
          signed 64-bit integer.

    `uint8'
          unsigned 8-bit integer.

    `uint16'
          unsigned 16-bit integer.

    `uint32'
          unsigned 32-bit integer.

    `uint64'
          unsigned 64-bit integer.

     The default for TYPE is `uint32'.

     *See also:* intmax, bitmax.

* Menu:

* Integer Arithmetic::


File: octave.info,  Node: Integer Arithmetic,  Up: Integer Data Types

4.3.1 Integer Arithmetic
------------------------

While many numerical computations can't be carried out in integers,
Octave does support basic operations like addition and multiplication
on integers. The operators `+', `-', `.*', and `./' works on integers
of the same type. So, it is possible to add two 32 bit integers, but
not to add a 32 bit integer and a 16 bit integer.

   The arithmetic operations on integers are performed by casting the
integer values to double precision values, performing the operation, and
then re-casting the values back to the original integer type. As the
double precision type of Octave is only capable of representing integers
with up to 53 bits of precision, it is not possible to perform
arithmetic of the 64 bit integer types.

   When doing integer arithmetic one should consider the possibility of
underflow and overflow. This happens when the result of the computation
can't be represented using the chosen integer type. As an example it is
not possible to represent the result of 10 - 20 when using unsigned
integers. Octave makes sure that the result of integer computations is
the integer that is closest to the true result. So, the result of 10 -
20 when using unsigned integers is zero.

   When doing integer division Octave will round the result to the
nearest integer. This is different from most programming languages,
where the result is often floored to the nearest integer. So, the
result of `int32(5)./int32(8)' is `1'.


File: octave.info,  Node: Bit Manipulations,  Next: Logical Values,  Prev: Integer Data Types,  Up: Numeric Data Types

4.4 Bit Manipulations
=====================

Octave provides a number of functions for the manipulation of numeric
values on a bit by bit basis. The basic functions to set and obtain the
values of individual bits are `bitset' and `bitget'.

 -- Function File: X = bitset (A, N)
 -- Function File: X = bitset (A, N, V)
     Set or reset bit(s) N of unsigned integers in A.  V = 0 resets and
     V = 1 sets the bits.  The lowest significant bit is: N = 1

          dec2bin (bitset (10, 1))
          => 1011


     *See also:* bitand, bitor, bitxor, bitget, bitcmp, bitshift,
     bitmax.

 -- Function File: X = bitget (A,N)
     Return the status of bit(s) N of unsigned integers in A the lowest
     significant bit is N = 1.

          bitget (100, 8:-1:1)
          => 0  1  1  0  0  1  0  0


     *See also:* bitand, bitor, bitxor, bitset, bitcmp, bitshift,
     bitmax.

   The arguments to all of Octave's bitwise operations can be scalar or
arrays, except for `bitcmp', whose K argument must a scalar. In the
case where more than one argument is an array, then all arguments must
have the same shape, and the bitwise operator is applied to each of the
elements of the argument individually. If at least one argument is a
scalar and one an array, then the scalar argument is duplicated.
Therefore

     bitget (100, 8:-1:1)

   is the same as

     bitget (100 * ones (1, 8), 8:-1:1)

   It should be noted that all values passed to the bit manipulation
functions of Octave are treated as integers. Therefore, even though the
example for `bitset' above passes the floating point value `10', it is
treated as the bits `[1, 0, 1, 0]' rather than the bits of the native
floating point format representation of `10'.

   As the maximum number that can be represented by a number is
important for bit manipulation, particularly when forming masks, Octave
supplies the function `bitmax'.

 -- Built-in Function:  bitmax ()
     Return the largest integer that can be represented as a floating
     point value.  On IEEE-754 compatiable systems, `bitmax' is `2^53 -
     1'.

   This is the double precision version of the functions `intmax',
previously discussed.

   Octave also include the basic bitwise 'and', 'or' and 'exclusive or'
operators.

 -- Built-in Function:  bitand (X, Y)
     Return the bitwise AND of nonnegative integers.  X, Y must be in
     range [0..bitmax]

     *See also:* bitor, bitxor, bitset, bitget, bitcmp, bitshift,
     bitmax.

 -- Built-in Function:  bitor (X, Y)
     Return the bitwise OR of nonnegative integers.  X, Y must be in
     range [0..bitmax]

     *See also:* bitor, bitxor, bitset, bitget, bitcmp, bitshift,
     bitmax.

 -- Built-in Function:  bitxor (X, Y)
     Return the bitwise XOR of nonnegative integers.  X, Y must be in
     range [0..bitmax]

     *See also:* bitand, bitor, bitset, bitget, bitcmp, bitshift,
     bitmax.

   The bitwise 'not' operator is unary operator that performs a logial
negation of each of the bits of the value. For this to make sense, the
mask against which the value is negated must be defined. Octave's
bitwise 'not' operator is `bitcmp'.

 -- Function File:  bitcmp (A, K)
     Return the K-bit complement of integers in A.  If K is omitted `k
     = log2 (bitmax) + 1' is assumed.

          bitcmp(7,4)
          => 8
          dec2bin(11)
          => 1011
          dec2bin(bitcmp(11, 6))
          => 110100


     *See also:* bitand, bitor, bitxor, bitset, bitget, bitcmp,
     bitshift, bitmax.

   Octave also includes the ability to left and right values bitwise.

 -- Built-in Function:  bitshift (A, K)
 -- Built-in Function:  bitshift (A, K, N)
     Return a K bit shift of N- digit unsigned integers in A.  A
     positive K leads to a left shift.  A negative value to a right
     shift.  If N is omitted it defaults to log2(bitmax)+1.  N must be
     in range [1,log2(bitmax)+1] usually [1,33]

          bitshift (eye (3), 1)
          =>
          2 0 0
          0 2 0
          0 0 2

          bitshift (10, [-2, -1, 0, 1, 2])
          => 2   5  10  20  40


     *See also:* bitand, bitor, bitxor, bitset, bitget, bitcmp, bitmax.

   Bits that are shifted out of either end of the value are lost. Octave
also uses arithmetic shifts, where the sign bit of the value is keep
during a right shift. For example

     bitshift (-10, -1)
     => -5
     bitshift (int8 (-1), -1)
     => -1

   Note that `bitshift (int8 (-1), -1)' is `-1' since the bit
representation of `-1' in the `int8' data type is `[1, 1, 1, 1, 1, 1,
1, 1]'.


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

4.5 Logical Values
==================

Octave has built-in support for logical values, i.e. variables that are
either `true' or `false'. When comparing two variables, the result will
be a logical value whose value depends on whether or not the comparison
is true.

   The basic logical operations are `&', `|', and `!', that corresponds
to "Logical And", "Logical Or", and "Logical Negation". These
operations all follow the rules of logic.

   It is also possible to use logical values as part of standard
numerical calculations. In this case `true' is converted to `1', and
`false' to 0, both represented using double precision floating point
numbers. So, the result of `true*22 - false/6' is `22'.

   Logical values can also be used to index matrices and cell arrays.
When indexing with a logical array the result will be a vector
containing the values corresponding to `true' parts of the logical
array.  The following example illustrates this.

     data = [ 1, 2; 3, 4 ];
     idx = (data <= 2);
     data(idx)
          => ans = [ 1; 4 ]

Instead of creating the `idx' array it is possible to replace
`data(idx)' with `data( data <= 2 )' in the above code.

   Besides when doing comparisons, logical values can be constructed by
casting numeric objects to logical values, or by using the `true' or
`false' functions.

 -- Function File:  logical (ARG)
     Convert ARG to a logical value.  For example,

          logical ([-1, 0, 1])

     is equivalent to

          [-1, 0, 1] != 0

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

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


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

4.6 Predicates for Numeric Objects
==================================

Since the type of a variable may change during the execution of a
program, it can be necessary to type checking at run-time. Doing this
also allows you to change the behaviour of a function depending on the
type of the input. As an example, this naive implementation of `abs'
returns the absolute value of the input if it is a real number, and the
length of the input if it is a complex number.

     function a = abs (x)
       if (isreal (x))
         a = sign (x) .* x;
       elseif (iscomplex (x))
         a = sqrt (real(x).^2 + imag(x).^2);
       endif
     endfunction

   The following functions are available for determining the type of a
variable.

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

     *See also:* size, rows, columns, length, isscalar, ismatrix.

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

     *See also:* size, rows, columns, length, isscalar, ismatrix.

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

     *See also:* size, rows, columns, length, ismatrix, isscalar,
     isvector.

 -- 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.  Matrix X
     is considered symmetric if `norm (X - X.', inf) / norm (X, inf) <
     TOL'.

     *See also:* size, rows, columns, length, ishermitian, ismatrix,
     isscalar, issquare, isvector.

 -- Function File:  isdefinite (X, TOL)
     Return 1 if X is symmetric positive definite within the tolerance
     specified by TOL or 0 if X is symmetric positive semidefinite.
     Otherwise, return -1.  If TOL is omitted, use a tolerance equal to
     100 times the machine precision.

     *See also:* issymmetric.

 -- Built-in Function:  islogical (X)
     Return true if X is a logical object.

 -- Function File:  isprime (N)
     Return true if N is a prime number, false otherwise.

     Something like the following is much faster if you need to test a
     lot of small numbers:

          T = ismember (N, primes (max (N (:))));

     If max(n) is very large, then you should be using special purpose
     factorization code.


     *See also:* primes, factor, gcd, lcm.


File: octave.info,  Node: Strings,  Next: Data Containers,  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.

   In double-quoted strings, the backslash character is used to
introduce "escape sequences" that represent other characters.  For
example, `\n' embeds a newline character in a double-quoted string and
`\"' embeds a double quote character.

   In single-quoted strings, backslash is not a special character.

   Here is an example showing the difference

     toascii ("\n")
         => 10
     toascii ('\n')
         => [ 92 110 ]

   You may also insert a single quote character in a single-quoted
string by using two single quote characters in succession.  For example,

     'I can''t escape'
         => I can't escape

   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::
* Comparing Strings::
* Manipulating Strings::
* String Conversions::
* Character Class Functions::


File: octave.info,  Node: Creating Strings,  Next: Comparing Strings,  Up: Strings

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

The easiest way to create a string is, as illustrated in the
introduction, to enclose a text in double-quotes or single-quotes. It
is however possible to create a string without actually writing a text.
The function `blanks' creates a string of a given length consisting
only of blank characters (ASCII code 32).

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

     *See also:* repmat.

   The string representation used by Octave is an array of characters,
so the result of `blanks(10)' is actually a row vector of length 10
containing the value 32 in all places. This lends itself to the obvious
generalisation to character matrices. Using a matrix of characters, it
is possible to represent a collection of same-length strings in one
variable. The convention used in Octave is that each row in a character
matrix is a separate string, but letting each column represent a string
is equally possible.

   The easiest way to create a character matrix is to put several
strings together into a matrix.

     collection = [ "String #1"; "String #2" ];

This creates a 2-by-9 character matrix.

   One relevant question is, what happens when character matrix is
created from strings of different length. The answer is that Octave
puts blank characters at the end of strings shorter than the longest
string. While it is possible to use a different character than the
blank character using the `string_fill_char' function, it shows a
problem with character matrices. It simply isn't possible to represent
strings of different lengths. The solution is to use a cell array of
strings, which is described in *note Cell Arrays of Strings::.

 -- 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:  strcat (S1, S2, ...)
     Return a string containing all the arguments concatenated.  For
     example,

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

 -- Function File:  strvcat (S_1, ..., S_N)
     Return a matrix containing the strings (and cell-strings) S_1,
     ..., S_N as its rows.  Each string is padded with blanks in order
     to form a valid matrix.  Unlike STR2MAT, empty strings are ignored.

     *See also:* strcat, str2mat.

 -- Function File:  strtrunc (S, N)
     Truncate the character string S to length N. If S is a char
     matrix, then the number of columns are adjusted.

     If S is a cell array of strings, then the operation is performed
     on its members and the new cell array is returned.

 -- Built-in Function: VAL = string_fill_char ()
 -- Built-in Function: OLD_VAL = string_fill_char (NEW_VAL)
     Query or set the internal variable used to pad all rows of a
     character matrix to the same length.  It must 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: S = mat2str (X, N)
 -- Function File: S = mat2str (..., 'class')
     Format real/complex numerical matrices as strings. This function
     returns values that are suitable for the use of the `eval'
     function.

     The precision of the values is given by N. If N is a scalar then
     both real and imaginary parts of the matrix are printed to the
     same precision. Otherwise `N (1)' defines the precision of the
     real part and `N (2)' defines the precision of the imaginary part.
     The default for N is 17.

     If the argument 'class' is given, then the class of X is included
     in the string in such a way that the eval will result in the
     construction of a matrix of the same class.

             mat2str( [ -1/3 + i/7; 1/3 - i/7 ], [4 2] )
          => '[-0.3333+0.14i;0.3333-0.14i]'
             mat2str( [ -1/3 +i/7; 1/3 -i/7 ], [4 2] )
          => '[-0.3333+0i,0+0.14i;0.3333+0i,-0-0.14i]'
             mat2str( int16([1 -1]), 'class')
          => 'int16([1,-1])'


     *See also:* sprintf, int2str.

 -- Function File:  num2str (N)
 -- Function File:  num2str (X, PRECISION)
 -- Function File:  num2str (X, FORMAT)
     Convert a number to a string.  This function is not very flexible.
     For better control over the results, use `sprintf' (*note
     Formatted Output::).

     *See also:* sprintf, int2str.

 -- Function File:  int2str (N)
     Convert an integer to a string.  This function is not very
     flexible.  For better control over the results, use `sprintf'
     (*note Formatted Output::).

     *See also:* sprintf, num2str.


File: octave.info,  Node: Comparing Strings,  Next: Manipulating Strings,  Prev: Creating Strings,  Up: Strings

5.2 Comparing Strings
=====================

Since a string is a character array comparison between strings work
element by element as the following example shows.

     GNU = "GNU's Not UNIX";
     spaces = (GNU == " ")
     => spaces =
           0   0   0   0   0   1   0   0   0   1   0   0   0   0

To determine if two functions are identical it is therefore necessary
to use the `strcmp' or `strncpm' functions. Similar functions exist for
doing case-insensitive comparisons.

 -- Built-in Function:  strcmp (S1, S2)
     Return 1 if the character strings S1 and S2 are the same, and 0
     otherwise.

     If either S1 or S2 is a cell array of strings, then an array of
     the same size is returned, containing the values described above
     for every member of the cell array. The other argument may also be
     a cell array of strings (of the same size or with only one
     element), char matrix or character string.

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

     *See also:* strcmpi, strncmp, strncmpi.

 -- Function File:  strcmpi (S1, S2)
     Ignoring case, return 1 if the character strings S1 and S2 are the
     same, and 0 otherwise.

     If either S1 or S2 is a cell array of strings, then an array of
     the same size is returned, containing the values described above
     for every member of the cell array. The other argument may also be
     a cell array of strings (of the same size or with only one
     element), char matrix or character string.

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

     *See also:* strcmp, strncmp, strncmpi.

 -- Built-in Function:  strncmp (S1, S2, N)
     Return 1 if the first N characters of strings S1 and S2 are the
     same, and 0 otherwise.

          strncmp ("abce", "abcd", 3)
               => 1

     If either S1 or S2 is a cell array of strings, then an array of
     the same size is returned, containing the values described above
     for every member of the cell array. The other argument may also be
     a cell array of strings (of the same size or with only one
     element), char matrix or character string.

          strncmp ("abce", {"abcd", "bca", "abc"}, 3)
               => [1, 0, 1]

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

     *See also:* strncmpi, strcmp, strcmpi.

 -- Function File:  strncmpi (S1, S2, N)
     Ignoring case, return 1 if the first N characters of character
     strings S1 and S2 are the same, and 0 otherwise.

     If either S1 or S2 is a cell array of strings, then an array of
     the same size is returned, containing the values described above
     for every member of the cell array. The other argument may also be
     a cell array of strings (of the same size or with only one
     element), char matrix or character string.

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

     *See also:* strcmp, strcmpi, strncmp.


File: octave.info,  Node: Manipulating Strings,  Next: String Conversions,  Prev: Comparing Strings,  Up: Strings

5.3 Manipulating Strings
========================

Octave supports a wide range of functions for manipulating strings.
Since a string is just a matrix, simple manipulations can be
accomplished using standard operators. The following example shows how
to replace all blank characters with underscores.

     quote = ...
       "First things first, but not necessarily in that order";
     quote( quote == " " ) = "_"
     => quote =
         First_things_first,_but_not_necessarily_in_that_order

   For more complex manipulations, such as searching, replacing, and
general regular expressions, the following functions come with Octave.

 -- Function File:  deblank (S)
     Remove trailing blanks and nulls from S.  If S is a matrix,
     DEBLANK trims each row to the length of longest string.  If S is a
     cell array, operate recursively on each element of the cell array.

 -- 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)
 -- Function File:  index (S, T, DIRECTION)
     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

     If DIRECTION is `"first"', return the first element found.  If
     DIRECTION is `"last"', return the last element found.  The
     `rindex' function is equivalent to `index' with DIRECTION set to
     `"last"'.

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

     *See also:* find, rindex.

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

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

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

     *See also:* find, index.

 -- Function File: IDX = strfind (STR, PATTERN)
 -- Function File: IDX = strfind (CELLSTR, PATTERN)
     Search for PATTERN in the string STR and return the starting index
     of every such occurrence in the vector IDX.  If there is no such
     occurrence, or if PATTERN is longer than STR, then IDX is the
     empty array `[]'.

     If the cell array of strings CELLSTR is specified instead of the
     string STR, then IDX is a cell array of vectors, as specified
     above.

     *See also:* findstr, strmatch, strcmp, strncmp, strcmpi, strncmpi.

 -- Function File:  strmatch (S, A, "exact")
     Return indices of entries of A that match the string S.  The
     second argument A may be a string matrix or a cell array of
     strings.  If the third argument `"exact"' is not given, then S
     only needs to match A up to the length of S.  Nul characters match
     blanks.  Results are returned as a column vector.

 -- Function File: [TOK, REM] = strtok (STR, DELIM)
     Find all characters up to but not including the first character
     which is in the string delim.  If REM is requested, it contains the
     remainder of the string, starting at the first deliminator. Leading
     delimiters are ignored.  If DELIM is not specified, space is
     assumed.


 -- Function File:  split (S, T, N)
     Divides the string S into pieces separated by T, returning the
     result in a string array (padded with blanks to form a valid
     matrix).  If the optional input N is supplied, split S into at
     most N different pieces.

     For example,

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

          split ("Test string", "t", 2)
          => "Tes    "
                  " string"

 -- 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, OFFSET, LEN)
     Return the substring of S which starts at character number OFFSET
     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 (OFFSET : (OFFSET + LEN - 1))'.

 -- Loadable Function: [S, E, TE, M, T, NM] = regexp (STR, PAT)
 -- Loadable Function: [...] = regexp (STR, PAT, OPTS, ...)
     Regular expression string matching. Matches PAT in STR and returns
     the position and matching substrings or empty values if there are
     none.

     The matched pattern PAT can include any of the standard regex
     operators, including:

    `.'
          Match any character

    `* + ? {}'
          Repetition operators, representing
         `*'
               Match zero or more times

         `+'
               Match one or more times

         `?'
               Match zero or one times

         `{}'
               Match range operator, which is of the form `{N}' to
               match exactly N times, `{M,}' to match M or more times,
               `{M,N}' to match between M and N times.

    `[...] [^...]'
          List operators, where for example `[ab]c' matches `ac' and
          `bc'

    `()'
          Grouping operator

    `|'
          Alternation operator. Match one of a choice of regular
          expressions. The alternatives must be delimited by the
          grouping operator `()' above

    `^ $'
          Anchoring operator. `^' matches the start of the string STR
          and `$' the end

     In addition the following escaped characters have special meaning.
     It should be noted that it is recommended to quote PAT in single
     quotes rather than double quotes, to avoid the escape sequences
     being interpreted by octave before being passed to `regexp'.

    `\b'
          Match a word boundary

    `\B'
          Match within a word

    `\w'
          Matches any word character

    `\W'
          Matches any non word character

    `\<'
          Matches the beginning of a word

    `\>'
          Matches the end of a word

    `\s'
          Matches any whitespace character

    `\S'
          Matches any non whitespace character

    `\d'
          Matches any digit

    `\D'
          Matches any non-digit

     The outputs of `regexp' by default are in the order as given below

    S
          The start indices of each of the matching substrings

    E
          The end indices of each matching substring

    TE
          The extents of each of the matched token surrounded by
          `(...)' in PAT.

    M
          A cell array of the text of each match.

    T
          A cell array of the text of each token matched.

    NM
          A structure containing the text of each matched named token,
          with the name being used as the fieldname. A named token is
          denoted as `(?<name>...)'

     Particular output arguments or the order of the output arguments
     can be selected by additional OPTS arguments. These are strings
     and the correspondence between the output arguments and the
     optional argument are

                   'start'              S                    
                   'end'                E                    
                   'tokenExtents'       TE                   
                   'match'              M                    
                   'tokens'             T                    
                   'names'              NM                   

     A further optional argument is 'once', that limits the number of
     returned matches to the first match. Additional arguments are

    matchcase
          Make the matching case sensitive.

    ignorecase
          Make the matching case insensitive.

    stringanchors
          Match the anchor characters at the beginning and end of the
          string.

    lineanchors
          Match the anchor characters at the beginning and end of the
          line.

    dotall
          The character `.' matches the newline character.

    dotexceptnewline
          The character `.' matches all but the newline character.

    freespacing
          The pattern can include arbitrary whitespace and comments
          starting with `#'.

    literalspacing
          The pattern is taken literally.

 -- Loadable Function: [S, E, TE, M, T, NM] = regexpi (STR, PAT)
 -- Loadable Function: [...] = regexpi (STR, PAT, OPTS, ...)
     Case insensitive regular expression string matching. Matches PAT in
     STR and returns the position and matching substrings or empty
     values if there are none. See `regexp' for more details

 -- Loadable Function: STRING = regexprep (STRING, PAT, REPSTR, OPTIONS)
     Replace matches of PAT in  STRING with REPSTR.

     The replacement can contain `$i', which substitutes for the ith
     set of parentheses in the match string.  E.g.,

             regexprep("Bill Dunn",'(\w+) (\w+)','$2, $1')
     returns "Dunn, Bill"

     OPTIONS may be zero or more of
    `once'
          Replace only the first occurrence of PAT in the result.

    `warnings'
          This option is present for compatibility but is ignored.

    `ignorecase or matchcase'
          Ignore case for the pattern matching (see `regexpi').
          Alternatively, use (?i) or (?-i) in the pattern.

    `lineanchors and stringanchors'
          Whether characters ^ and $ match the beginning and ending of
          lines.  Alternatively, use (?m) or (?-m) in the pattern.

    `dotexceptnewline and dotall'
          Whether . matches newlines in the string.  Alternatively, use
          (?s) or (?-s) in the pattern.

    `freespacing or literalspacing'
          Whether whitespace and # comments can be used to make the
          regular expression more readable.  Alternatively, use (?x) or
          (?-x) in the pattern.



     *See also:* regexp,regexpi.


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

5.4 String Conversions
======================

Octave supports various kinds of conversions between strings and
numbers. As an example, it is possible to convert a string containing a
hexadecimal number to a floating point number.

     hex2dec ("FF")
          => ans = 255

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

          bin2dec ("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.

     *See also:* dec2hex, base2dec, dec2base, hex2dec, dec2bin.

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

     *See also:* bin2dec, dec2base, base2dec, hex2dec, dec2hex.

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

     *See also:* hex2dec, dec2base, base2dec, bin2dec, dec2bin.

 -- Function File:  hex2dec (S)
     Return 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.

     *See also:* dec2hex, base2dec, dec2base, bin2dec, dec2bin.

 -- Function File:  dec2base (N, B, LEN)
     Return a string of symbols in base B corresponding to 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.

     *See also:* base2dec, dec2bin, bin2dec, hex2dec, dec2hex.

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


     *See also:* dec2base, dec2bin, bin2dec, hex2dec, dec2hex.

 -- Function File: [NUM, STATUS, STRARRAY] = str2double (STR, CDELIM,
          RDELIM, DDELIM)
     Convert strings into numeric values.

     `str2double' can replace `str2num', but avoids the use of `eval'
     on unknown data.

     STR can be the form `[+-]d[.]dd[[eE][+-]ddd]' in which `d' can be
     any of digit from 0 to 9, and `[]' indicate optional elements.

     NUM is the corresponding numeric value.  If the conversion fails,
     status is -1 and NUM is NaN.

     STATUS is 0 if the conversion was successful and -1 otherwise.

     STRARRAY is a cell array of strings.

     Elements which are not defined or not valid return NaN and the
     STATUS becomes -1.

     If STR is a character array or a cell array of strings, then NUM
     and STATUS return matrices of appropriate size.

     STR can also contain multiple elements separated by row and column
     delimiters (CDELIM and RDELIM).

     The parameters CDELIM, RDELIM, and DDELIM are optional column,
     row, and decimal delimiters.

     The default row-delimiters are newline, carriage return and
     semicolon (ASCII 10, 13 and 59).  The default column-delimiters
     are tab, space and comma (ASCII 9, 32, and 44).  The default
     decimal delimiter is `.' (ASCII 46).

     CDELIM, RDELIM, and DDELIM must contain only nul, newline,
     carriage return, semicolon, colon, slash, tab, space, comma, or
     `()[]{}' (ASCII 0, 9, 10, 11, 12, 13, 14, 32, 33, 34, 40, 41, 44,
     47, 58, 59, 91, 93, 123, 124, 125).

     Examples:

          str2double ("-.1e-5")
          => -1.0000e-006

          str2double (".314e1, 44.44e-1, .7; -1e+1")
          =>
             3.1400    4.4440    0.7000
           -10.0000       NaN       NaN

          line = "200, 300, NaN, -inf, yes, no, 999, maybe, NaN";
          [x, status] = str2double (line)
          => x =
              200   300   NaN  -Inf   NaN   NaN   999   NaN   NaN
          => status =
                0     0     0     0    -1    -1     0    -1     0

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


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

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

 -- Function File:  isletter (S)
     Returns true if S is a letter false otherwise.

     *See also:* isalpha.

 -- 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 Containers,  Next: Variables,  Prev: Strings,  Up: Top

6 Data Containers
*****************

Octave includes support for two different mechanisms to contain
arbitrary data types in the same variable. Structures, which are C-like,
and are indexed with named fields, and cell arrays, where each element
of the array can have a different data type and or shape.

* Menu:

* Data Structures::
* Cell Arrays::
* Comma Separated Lists::


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

6.1 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 Function: VAL = struct_levels_to_print ()
 -- Built-in Function: OLD_VAL = struct_levels_to_print (NEW_VAL)
     Query or set the internal variable that specifies the number of
     structure levels to display.

   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 Looping
Over Structure Elements::)

* Menu:

* Structure Arrays::
* Creating Structures::
* Manipulating Structures::
* Processing Data in Structures::


File: octave.info,  Node: Structure Arrays,  Next: Creating Structures,  Up: Data Structures

6.1.1 Structure Arrays
----------------------

A structure array is a particular instance of a structure, where each of
the fields of the structure is represented by a cell array. Each of
these cell arrays has the same dimensions. An example of the creation of
a structure array is

     x(1).a = "string1"
     x(2).a = "string2"
     x(1).b = 1
     x(2).b = 2

which creates a 2-by-1 structure array with two fields. As previously,
to print the value of the structure array, you can type its name:

     octave:2> x
     x =
     {
       a =

       (,
         [1] = string1
         [2] = string2
       ,)

       b =

       (,
         [1] =  1
         [2] =  2
       ,)

     }

   Individual elements of the structure array can be returned by
indexing the variable like `X (1)', which returns a structure with the
two fields like

     octave:2> x(1)
     ans =
     {
       a = string1
       b =  1
     }

   Furthermore, the structure array can return a comma separated list
(*note Comma Separated Lists::), if indexed by one of itself field
names. For example

     octave:3> x.a
     ans =

     (,
       [1] = string1
       [2] = string2
     ,)

   The function `size' with return the size of the structure. For the
example above

     octave:4> size(x)
     ans =

        1   2

   Elements can be deleted from a structure array in a similar manner
to a numerical array, by assigning the elements to an empty matrix. For
example

     in = struct ("call1", {x, Inf, "last"},
                  "call2", {x, Inf, "first"});
     in (1, :) = []
     => in =
           {
             call1 =

             (,
               [1] = Inf
               [2] = last
             ,)

             call2 =

             (,
               [1] = Inf
               [2] = first
             ,)

           }


File: octave.info,  Node: Creating Structures,  Next: Manipulating Structures,  Prev: Structure Arrays,  Up: Data Structures

6.1.2 Creating Structures
-------------------------

As well as indexing a structure with ".", Octave can create a structure
with the `struct' command. `struct' takes pairs of arguments, where the
first argument in the pair is the fieldname to include in the structure
and the second is a scalar or cell array, representing the values to
include in the structure or structure array. For example

     struct ("field1", 1, "field2", 2)
     => ans =
           {
             field1 =  1
             field2 =  2
           }

   If the values passed to `struct' are a mix of scalar and cell
arrays, then the scalar arguments are expanded to create a structure
array with a consistent dimension. For example

     struct ("field1", {1, "one"}, "field2", {2, "two"},
             "field3", 3)
     => ans =
           {
             field1 =

             (,
               [1] =  1
               [2] = one
             ,)

             field2 =

             (,
               [1] =  2
               [2] = two
             ,)

             field3 =

             (,
               [1] =  3
               [2] =  3
             ,)

           }

 -- Built-in Function:  struct ("field", VALUE, "field", VALUE, ...)
     Create a structure and initialize its value.

     If the values are cell arrays, create a structure array and
     initialize its values.  The dimensions of each cell array of
     values must match.  Singleton cells and non-cell values are
     repeated so that they fill the entire array.  If the cells are
     empty, create an empty structure array with the specified field
     names.

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

   Additional functions that can manipulate the fields of a structure
are listed below.

 -- Built-in Function:  rmfield (S, F)
     Remove field F from the structure S.  If F is a cell array of
     character strings or a character array, remove the named fields.

     *See also:* cellstr, iscellstr, setfield.

 -- Function File: [K1, ..., V1] = setfield (S, K1, V1, ...)
     Set field members in a structure.

          oo(1,1).f0= 1;
          oo = setfield(oo,{1,2},'fd',{3},'b', 6);
          oo(1,2).fd(3).b == 6
          => ans = 1

     Note that this function could be written

                   i1= {1,2}; i2= 'fd'; i3= {3}; i4= 'b';
                   oo( i1{:} ).( i2 )( i3{:} ).( i4 ) == 6;


     *See also:* getfield, rmfield, isfield, isstruct, fieldnames,
     struct.

 -- Function File: [T, P] = orderfields (S1, S2)
     Return a struct with fields arranged alphabetically or as specified
     by S2 and a corresponding permutation vector.

     Given one struct, arrange field names in S1 alphabetically.

     Given two structs, arrange field names in S1 as they appear in S2.
     The second argument may also specify the order in a permutation
     vector or a cell array of strings.


     *See also:* getfield, rmfield, isfield, isstruct, fieldnames,
     struct.


File: octave.info,  Node: Manipulating Structures,  Next: Processing Data in Structures,  Prev: Creating Structures,  Up: Data Structures

6.1.3 Manipulating Structures
-----------------------------

Other functions that can manipulate the fields of a structure are given
below.

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

 -- Function File: [V1, ...] = getfield (S, KEY, ...)
     Extract fields from a structure. For example

          ss(1,2).fd(3).b=5;
          getfield (ss, {1,2}, "fd", {3}, "b")
          => ans = 5

     Note that the function call in the previous example is equivalent
     to the expression

                   i1= {1,2}; i2= "fd"; i3= {3}; i4= "b";
                   ss(i1{:}).(i2)(i3{:}).(i4)


     *See also:* setfield, rmfield, isfield, isstruct, fieldnames,
     struct.

 -- Function File:  substruct (TYPE, SUBS, ...)
     Create a subscript structure for use with `subsref' or `subsasgn'.

     *See also:* subsref, subsasgn.


File: octave.info,  Node: Processing Data in Structures,  Prev: Manipulating Structures,  Up: Data Structures

6.1.4 Processing Data in Structures
-----------------------------------

The simplest way to process data in a structure is within a `for' loop
(*note Looping Over Structure Elements::). A similar effect can be
achieved with the `structfun' function, where a user defined function
is applied to each field of the structure.

 -- Function File:  structfun (FUNC, S)
 -- Function File: [A, B] = structfun (...)
 -- Function File:  structfun (..., 'ErrorHandler', ERRFUNC)
 -- Function File:  structfun (..., 'UniformOutput', VAL)
     Evaluate the function named NAME on the fields of the structure S.
     The fields of S are passed to the function FUNC individually.

     `structfun' accepts an arbitrary function FUNC in the form of an
     inline function, function handle, or the name of a function (in a
     character string). In the case of a character string argument, the
     function must accept a single argument named X, and it must return
     a string value. If the function returns more than one argument,
     they are returned as separate output variables.

     If the param 'UniformOutput' is set to true (the default), then
     the function must return either a single element which will be
     concatenated into the return value. If 'UniformOutput is false,
     the outputs placed in a structure with the same fieldnames as the
     input structure.

          s.name1 = "John Smith";
          s.name2 = "Jill Jones";
          structfun (@(x) regexp (x, '(\w+)$', 'matches'){1}, s,
                     'UniformOutput', false)

     Given the parameter 'ErrorHandler', then ERRFUNC defines a
     function to call in case FUNC generates an error. The form of the
     function is

          function [...] = errfunc (SE, ...)

     where there is an additional input argument to ERRFUNC relative to
     FUNC, given by SE. This is a structure with the elements
     'identifier', 'message' and 'index', giving respectively the error
     identifier, the error message, and the index into the input
     arguments of the element that caused the error.

     *See also:* cellfun, arrayfun.

   Alternatively, to process the data in a structure, the structure
might be converted to another type of container before being treated.

 -- Built-in Function:  struct2cell (S)
     Create a new cell array from the objects stored in the struct
     object.  If F is the number of fields in the structure, the
     resulting cell array will have a dimension vector corresponding to
     `[F size(S)]'.

     *See also:* cell2struct, fieldnames.


File: octave.info,  Node: Cell Arrays,  Next: Comma Separated Lists,  Prev: Data Structures,  Up: Data Containers

6.2 Cell Arrays
===============

It can be both necessary and convenient to store several variables of
different size or type in one variable. A cell array is a container
class able to do just that. In general cell arrays work just like
N-dimensional arrays, with the exception of the use of `{' and `}' as
allocation and indexing operators.

   As an example, the following code creates a cell array containing a
string and a 2-by-2 random matrix

     c = {"a string", rand(2, 2)};

And a cell array can be indexed with the { and } operators, so the
variable created in the previous example can be indexed like this

     c{1}
          => ans = a string

As with numerical arrays several elements of a cell array can be
extracted by indexing with a vector of indexes

     c{1:2}
          => ans =

               (,
                 [1] = a string
                 [2] =

                    0.593993   0.627732
                    0.377037   0.033643

               ,)

   The indexing operators can also be used to insert or overwrite
elements of a cell array. The following code inserts the scalar 3 on the
third place of the previously created cell array

     c{3} = 3
          => c =

              {
                [1,1] = a string
                [1,2] =

                   0.593993   0.627732
                   0.377037   0.033643

                [1,3] =  3
              }

   In general nested cell arrays are displayed hierarchically as above.
In some circumstances it makes sense to reference them by their index,
and this can be performed by the `celldisp' function.

 -- Function File:  celldisp (C, NAME)
     Recursively display the contents of a cell array. By default the
     values are displayed with the name of the variable C. However,
     this name can be replaced with the variable NAME.

     *See also:* disp.

* Menu:

* Creating Cell Arrays::
* Indexing Cell Arrays::
* Cell Arrays of Strings::
* Processing Data in Cell Arrays::


File: octave.info,  Node: Creating Cell Arrays,  Next: Indexing Cell Arrays,  Up: Cell Arrays

6.2.1 Creating Cell Array
-------------------------

The introductory example showed how to create a cell array containing
currently available variables. In many situations, however, it is useful
to create a cell array and then fill it with data.

   The `cell' function returns a cell array of a given size, containing
empty matrices. This function works very similar to the `zeros'
function for creating new numerical arrays. The following example
creates a 2-by-2 cell array containing empty matrices

     c = cell(2,2)
          => c =

              {
                [1,1] = [](0x0)
                [2,1] = [](0x0)
                [1,2] = [](0x0)
                [2,2] = [](0x0)
              }

   Just like numerical arrays, cell arrays can be multidimensional. The
`cell' function accepts any number of positive integers to describe the
size of the returned cell array. It is also possible to set the size of
the cell array through a vector of positive integers. In the following
example two cell arrays of equal size is created, and the size of the
first one is displayed

     c1 = cell(3, 4, 5);
     c2 = cell( [3, 4, 5] );
     size(c1)
          => ans =
              3   4   5

As can be seen, the `size' function also works for cell arrays. As do
the other functions describing the size of an object, such as `length',
`numel', `rows', and `columns'.

   An alternative to creating empty cell arrays, and then filling them,
it is possible to convert numerical arrays into cell arrays using the
`num2cell' and `mat2cell' functions.

 -- 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:  iscell (X)
     Return true if X is a cell array object.  Otherwise, return false.

 -- Loadable Function: C = num2cell (M)
 -- Loadable Function: C = num2cell (M, DIM)
     Convert the matrix M into a cell array. If DIM is defined, the
     value C is of dimension 1 in this dimension and the elements of M
     are placed in slices in C.

     *See also:* mat2cell.

 -- Loadable Function: B = mat2cell (A, M, N)
 -- Loadable Function: B = mat2cell (A, D1, D2, ...)
 -- Loadable Function: B = mat2cell (A, R)
     Convert the matrix A to a cell array. If A is 2-D, then it is
     required that `sum (M) == size (A, 1)' and `sum (N) == size (A,
     2)'. Similarly, if A is a multi-dimensional and the number of
     dimensional arguments is equal to the dimensions of A, then it is
     required that `sum (DI) == size (A, i)'.

     Given a single dimensional argument R, the other dimensional
     arguments are assumed to equal `size (A,I)'.

     An example of the use of mat2cell is

          mat2cell (reshape(1:16,4,4),[3,1],[3,1])
          => {
            [1,1] =

               1   5   9
               2   6  10
               3   7  11

            [2,1] =

               4   8  12

            [1,2] =

              13
              14
              15

            [2,2] = 16
          }


     *See also:* num2cell, cell2mat.


File: octave.info,  Node: Indexing Cell Arrays,  Next: Cell Arrays of Strings,  Prev: Creating Cell Arrays,  Up: Cell Arrays

6.2.2 Indexing Cell Arrays
--------------------------

As shown in the introductory example elements can be inserted from cell
arrays using the `{' and `}' operators. Besides the change of
operators, indexing works for cell arrays like for multidimensional
arrays.  As an example, all the rows of the first and third column of a
cell array can be set to `0' with the following code

     c{:, [1, 3]} = 0;

   Accessing values in a cell array is, however, different from the same
operation for numerical arrays. Accessing a single element of a cell
array is very similar to numerical arrays, for example

     element = c{1, 2};

This will, however, _not_ work when accessing multiple elements of a
cell array, because it might not be possible to represent all elements
with a single variable as is the case with numerical arrays.

   Accessing multiple elements of a cell array with the `{' and `}'
operators will result in a comma-separated list (*note Comma Separated
Lists::) of all the requested elements as discussed later.

   One distinction between `{' and `(' to index cell arrays is in the
deletion of elements from the cell array. In a similar manner to a
numerical array the `()' operator can be used to delete elements from
the cell array. The `{}' operator however will remove the elements of
the cell array, but not delete the space for them. For example

     x = {"1", "2"; "3", "4"};
     x{1, :} = []
     => x =
           {
             [1,1] = [](0x0)
             [2,1] = 3
             [1,2] = [](0x0)
             [2,2] = 4
           }

     x(1, :) = []
     => x =
           {
             [1,1] = 3
             [1,2] = 4
           }


File: octave.info,  Node: Cell Arrays of Strings,  Next: Processing Data in Cell Arrays,  Prev: Indexing Cell Arrays,  Up: Cell Arrays

6.2.3 Cell Arrays of Strings
----------------------------

One common use of cell arrays is to store multiple strings in the same
variable. It is possible to store multiple strings in a character matrix
by letting each row be a string. This, however, introduces the problem
that all strings must be of equal length. Therefore it is recommended to
use cell arrays to store multiple strings. If, however, the character
matrix representation is required for an operation, it can be converted
to a cell array of strings using the `cellstr' function

     a = ["hello"; "world"];
     c = cellstr (a)
          => c =
              {
                [1,1] = hello
                [2,1] = world
              }

   One further advantage of using cell arrays to store multiple
strings, is that most functions for string manipulations included with
Octave support this representation. As an example, it is possible to
compare one string with many others using the `strcmp' function. If one
of the arguments to this function is a string and the other is a cell
array of strings, each element of the cell array will be compared the
string argument,

     c = {"hello", "world"};
     strcmp ("hello", c)
          => ans =
             1   0

The following functions for string manipulation support cell arrays of
strings, `strcmp', `strcmpi', `strncmp', `strncmpi', `str2double',
`str2mat', `strappend', `strtrunc', `strvcat', `strfind', and
`strmatch'.

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

 -- Built-in Function:  iscellstr (CELL)
     Return true if every element of the cell array CELL is a character
     string

 -- Function File: [IDXVEC, ERRMSG] = cellidx (LISTVAR, STRLIST)
     Return indices of string entries in LISTVAR that match strings in
     STRLIST.

     Both LISTVAR and STRLIST may be passed as strings or string
     matrices.  If they are passed as string matrices, each entry is
     processed by `deblank' prior to searching for the entries.

     The first output is the vector of indices in LISTVAR.

     If STRLIST contains a string not in LISTVAR, then an error message
     is returned in ERRMSG.  If only one output argument is requested,
     then CELLIDX prints ERRMSG to the screen and exits with an error.


File: octave.info,  Node: Processing Data in Cell Arrays,  Prev: Cell Arrays of Strings,  Up: Cell Arrays

6.2.4 Processing Data in Cell Arrays
------------------------------------

Data that is stored in a cell array can be processed in several ways
depending on the actual data. The most simple way to process that data
is to iterate through it using one or more `for' loops. The same idea
can be implemented easier through the use of the `cellfun' function
that calls a user specified function on all elements of a cell array.

 -- Loadable Function:  cellfun (NAME, C)
 -- Loadable Function:  cellfun ("size", C, K)
 -- Loadable Function:  cellfun ("isclass", C, CLASS)
 -- Loadable Function:  cellfun (FUNC, C)
 -- Loadable Function:  cellfun (FUNC, C, D)
 -- Loadable Function: [A, B] = cellfun (...)
 -- Loadable Function:  cellfun (..., 'ErrorHandler', ERRFUNC)
 -- Loadable Function:  cellfun (..., 'UniformOutput', VAL)
     Evaluate the function named NAME on the elements of the cell array
     C.  Elements in C are passed on to the named function
     individually.  The function NAME can be one of the functions

    `isempty'
          Return 1 for empty elements.

    `islogical'
          Return 1 for logical elements.

    `isreal'
          Return 1 for real elements.

    `length'
          Return a vector of the lengths of cell elements.

    `ndims'
          Return the number of dimensions of each element.

    `prodofsize'
          Return the product of dimensions of each element.

    `size'
          Return the size along the K-th dimension.

    `isclass'
          Return 1 for elements of CLASS.

     Additionally, `cellfun' accepts an arbitrary function FUNC in the
     form of an inline function, function handle, or the name of a
     function (in a character string). In the case of a character string
     argument, the function must accept a single argument named X, and
     it must return a string value. The function can take one or more
     arguments, with the inputs args given by C, D, etc. Equally the
     function can return one or more output arguments. For example

          cellfun (@atan2, {1, 0}, {0, 1})
          =>ans = [1.57080   0.00000]

     Note that the default output argument is an array of the same size
     as the input arguments.

     If the param 'UniformOutput' is set to true (the default), then
     the function must return either a single element which will be
     concatenated into the return value. If 'UniformOutput is false,
     the outputs are concatenated in a cell array. For example

          cellfun ("tolower(x)", {"Foo", "Bar", "FooBar"},
                   "UniformOutput",false)
          => ans = {"foo", "bar", "foobar"}

     Given the parameter 'ErrorHandler', then ERRFUNC defines a
     function to call in case FUNC generates an error. The form of the
     function is

          function [...] = errfunc (S, ...)

     where there is an additional input argument to ERRFUNC relative to
     FUNC, given by S. This is a structure with the elements
     'identifier', 'message' and 'index', giving respectively the error
     identifier, the error message, and the index into the input
     arguments of the element that caused the error. For example

          function y = foo (s, x), y = NaN; endfunction
          cellfun (@factorial, {-1,2},'ErrorHandler',@foo)
          => ans = [NaN 2]


     *See also:* isempty, islogical, isreal, length, ndims, numel,
     size, isclass.

   An alternative is to convert the data to a different container, such
as a matrix or a data structure.  Depending on the data this is possible
using the `cell2mat' and `cell2struct' functions.

 -- Function File: M = cell2mat (C)
     Convert the cell array C into a matrix by concatenating all
     elements of C into a hyperrectangle.  Elements of C must be
     numeric, logical or char, and `cat' must be able to concatenate
     them together.

     *See also:* mat2cell, num2cell.

 -- Built-in Function:  cell2struct (CELL, FIELDS, DIM)
     Convert CELL to a structure. The number of fields in FIELDS must
     match the number of elements in CELL along dimension DIM, that is
     `numel (FIELDS) == size (CELL, DIM)'.

          A = cell2struct ({'Peter', 'Hannah', 'Robert';
                             185, 170, 168},
                           {'Name','Height'}, 1);
          A(1)
          => ans =
                {
                  Height = 185
                  Name   = Peter
                }


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

6.3 Comma Separated Lists
=========================

Comma separated lists are the basic argument type to all Octave
functions. In the example

     max (A, B)

`A, B' is a comma separated list. Comma separated lists can appear on
both the right and left hand side of an equation. For example

     [I, J] = ceil (find (X, [], "last"));

where `I, J' is equally a comma separated list. Comma separated lists
can not be directly manipulated by the user. However, both structures
and cell arrays can be converted into comma separated lists, which
makes them useful to keep the input arguments and return values of
functions organized. Another example of where a comma separated list
can be used is in the creation of a new array. If all the accessed
elements of a cell array are scalars or column vectors, they can be
concatenated into a new column vector containing the elements, by
surrounding the list with `[' and `]' as in the following example

     a = {1, [2, 3], 4};
     b = [a{:}]
          => b =
              1   2   3   4

   It is also possible to pass the accessed elements directly to a
function.  The list of elements from the cell array will be passed as an
argument list to a given function as if it is called with the elements
as arguments.  The two calls to `printf' in the following example are
identical but the latter is simpler and handles more situations

     c = {"GNU", "Octave", "is", "Free", "Software"};
     printf ("%s ", c{1}, c{2}, c{3}, c{4}, c{5});
          -| GNU Octave is Free Software
     printf ("%s ", c{:});
          -| GNU Octave is Free Software

   Just like it is possible to create a numerical array from selected
elements of a cell array, it is possible to create a new cell array
containing the selected elements. By surrounding the list with `{' and
`}' a new cell array will be created, like the following example
illustrates

     a = {1, rand(2, 2), "three"};
     b = { a{ [1, 3] } }
          => b =
              {
                [1,1] =  1
                [1,2] = three
              }

This syntax is however a bit cumbersome, and since this is a common
operation, it is possible to achieve the same using the `(' and `)'
operators for indexing. When a cell array is indexed using the `(' and
`)' operators a new cell array containing the selected elements. Using
this syntax, the previous example can be simplified into the following

     a = {1, rand(2, 2), "three"};
     b = a( [1, 3] )
          => b =
              {
                [1,1] =  1
                [1,2] = three
              }

   A comma separated list can equally appear on the left-hand side of an
assignment. An example is

     in {1} = ceil (rand (10, 1));
     in {2} = [];
     in {3} = "last";
     in {4} = "first";
     out = cell (4, 1);
     [out{1:2}] = find (in{1 : 3});
     [out{3:4}] = find (in{[1, 2, 4]});

   Structure arrays can equally be used to create comma separated
lists. This is done by addresses one of the fields of a structure
array. For example

     x = ceil (randn (10, 1));
     in = struct ("call1", {x, Inf, "last"},
                  "call2", {x, Inf, "first"});
     out = struct ("call1", cell (2, 1), "call2", cell (2, 1));
     [out.call1] = find (in.call1);
     [out.call2] = find (in.call2);


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

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

 -- Built-in Function:  isvarname (NAME)
     Return true if NAME is a valid variable name

* 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

7.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.  Issuing a `clear
gvar' command does not change the above behavior, but `clear all' does.

   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

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

   The following example uses a persistent variable to create a function
that prints the number of times it has been called.

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

     for i = 1:3
       count_calls ();
     endfor

     -| 'count_calls' has been called 1 times
     -| 'count_calls' has been called 2 times
     -| 'count_calls' has been called 3 times

   As the example shows, 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'.

   Like global variables, a persistent variable may only be initialized
once.  For example, after executing the following code

     persistent pvar = 1
     persistent pvar = 2

the value of the persistent variable `pvar' is 1, not 2.

   If a persistent variable is declared but not initialized to a
specific value, it will contain an empty matrix.  So, it is also
possible to initialize a persistent variable by checking whether it is
empty, as the following example illustrates.

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

This implementation behaves in exactly the same way as the previous
implementation of `count_calls'.

   The value of a persistent variable is kept in memory until it is
explicitly cleared.  Assuming that the implementation of `count_calls'
is saved on disc, we get the following behaviour.

     for i = 1:2
       count_calls ();
     endfor
     -| 'count_calls' has been called 1 times
     -| 'count_calls' has been called 2 times

     clear
     for i = 1:2
       count_calls();
     endfor
     -| 'count_calls' has been called 3 times
     -| 'count_calls' has been called 4 times

     clear all
     for i = 1:2
       count_calls();
     endfor
     -| 'count_calls' has been called 1 times
     -| 'count_calls' has been called 2 times

     clear count_calls
     for i = 1:2
       count_calls();
     endfor
     -| 'count_calls' has been called 1 times
     -| 'count_calls' has been called 2 times

That is, the persistent variable is only removed from memory when the
function containing the variable is removed.  Note that if the function
definition is typed directly into the Octave prompt, the persistent
variable will be cleared by a simple `clear' command as the entire
function definition will be removed from memory.  If you do not want a
persistent variable to be removed from memory even if the function is
cleared, you should use the `mlock' function as described in *Note
Function Locking::.


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

7.3 Status of Variables
=======================

When creating simple one-shot programs it can be very convenient to see
which variables are available at the prompt. The function `who' and its
siblings `whos' and `whos_line_format' will show different information
about what is in memory, as the following shows.

     str = "A random string";
     who -variables
          -| *** local user variables:
          -|
          -| __nargin__  str

 -- 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 functions.  This includes all currently
          compiled function files, but does not include all function
          files that are in the search path.

    `-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 Function: VAL = whos_line_format ()
 -- Built-in Function: OLD_VAL = whos_line_format (NEW_VAL)
     Query or set the format string used by the `whos'.

     The following escape sequences may be used in the format:
    `%b'
          Prints number of bytes occupied by variables.

    `%c'
          Prints class names of variables.

    `%e'
          Prints elements held by variables.

    `%n'
          Prints variable names.

    `%p'
          Prints protection attributes 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.

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

   Instead of displaying which variables are in memory, it is possible
to determine if a given variable is available. That way it is possible
to alter the behaviour of a program depending on the existence of a
variable. The following example illustrates this.

     if (! exist ("meaning", "var"))
       disp ("The program has no 'meaning'");
     endif

 -- Built-in Function:  exist (NAME, TYPE)
     Return 1 if the name exists as a variable, 2 if the name is an
     absolute file name, an ordinary file in Octave's `path', or (after
     appending `.m') a function file in Octave's `path', 3 if the name
     is a `.oct' or `.mex' file in Octave's `path', 5 if the name is a
     built-in function, 7 if the name is a directory, 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 search path.  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.

   Usually Octave will manage the memory, but sometimes it can be
practical to remove variables from memory manually. This is usually
needed when working with large variables that fill a substantial part
of the memory.  On a computer that uses the IEEE floating point format,
the following program allocates a matrix that requires around 128 MB
memory.

     large_matrix = zeros (4000, 4000);

Since having this variable in memory might slow down other computations,
it can be necessary to remove it manually from memory. The `clear'
function allows this.

 -- Command: clear [options] 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.

     The following options are available in both long and short form
    `-all, -a'
          Clears all local and global user-defined variables and all
          functions from the symbol table.

    `-exclusive, -x'
          Clears the variables that don't match the following pattern.

    `-functions, -f'
          Clears the function names and the built-in symbols names.

    `-global, -g'
          Clears the global symbol names.

    `-variables, -v'
          Clears the local variable names.
     With the execption of `exclusive', all long options can be used
     without the dash as well.

   Information about a function or variable such as it's location in the
file system can also be acquired from within Octave. This is usually
only useful during development of programs, and not within a program.

 -- 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 whether each NAME is user-defined or
     built-in; the `-q' option suppresses this behaviour.

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

     *See also:* help, lookfor.


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

7.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, 3.0.3) and ARCH stands for the
type of system for which Octave was compiled (for example,
`x86_64-unknown-linux-gnu').

`EDITOR'
     *Note Commands For History::.

     Default value: `"emacs"'.

`EXEC_PATH'
     *Note Controlling Subprocesses::.

     Default value: `":$PATH"'.

`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: `"+ "'.

`beep_on_error'
     *Note Errors and Warnings::.

     Default value: 0.

`completion_append_char'
     *Note Commands For Completion::.

     Default value: `" "'.

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


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

7.5 Defaults from the Environment
=================================

Octave uses the values of the following environment variables to set the
default values for the corresponding built-in or internal 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::.

     Internal variable changed by function `path'.  Command-line
     argument: `--path'.

`OCTAVE_INFO_FILE'
     *Note Getting Help::.

     Internal variable changed by function `info_file'.  Command-line
     argument: `--info-file'.

`OCTAVE_INFO_PROGRAM'
     *Note Getting Help::.

     Internal variable changed by function `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

8 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

8.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 index expression.  Matrices may be
indexed using one or two indices.  When using a single index
expression, the elements of the matrix are taken in column-first order;
the dimensions of the output match those of the index expression.  For
example,
     a (2)       # a scalar
     a (1:2)     # a row vector
     a ([1; 2])  # a column vector

   As a special case, when a colon is used as a single index, the output
is a column vector containing all the elements of the vector or matrix.
For example
     a (:)       # a column vector

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

   It is also possible to create a matrix with different values. The
following example creates a 10 dimensional row vector a containing the
values a(i) = sqrt(i).

     for i = 1:10
       a(i) = sqrt (i);
     endfor

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.

 -- Built-in Function:  subsref (VAL, IDX)
     Perform the subscripted element selection operation according to
     the subscript specified by IDX.

     The subscript IDX is expected to be a structure array with fields
     `type' and `subs'.  Valid values for `type' are `"()"', `"{}"',
     and `"."'.  The `subs' field may be either `":"' or a cell array
     of index values.

     The following example shows how to extract the two first columns of
     a matrix

          val = magic(3)
               => val = [ 8   1   6
                          3   5   7
                          4   9   2 ]
          idx.type = "()";
          idx.subs = {":", 1:2};
          subsref(val, idx)
               => [ 8   1
                    3   5
                    4   9 ]

     Note that this is the same as writing `val(:,1:2)'.

     *See also:* subsasgn, substruct.

 -- Function File: IND = sub2ind (DIMS, I, J)
 -- Function File: IND = sub2ind (DIMS, S1, S2, ..., SN)
     Convert subscripts into a linear index.

     The following example shows how to convert the two-dimensional
     index `(2,3)' of a 3-by-3 matrix to a linear index.

          linear_index = sub2ind ([3, 3], 2, 3)
          => 8


     *See also:* ind2sub.

 -- Function File: [S1, S2, ..., SN] = ind2sub (DIMS, IND)
     Convert a linear index into subscripts.

     The following example shows how to convert the linear index `8' in
     a 3-by-3 matrix into a subscript.

          [r, c] = ind2sub ([3, 3], 8)
          => r =  2
          c =  3


     *See also:* sub2ind.


File: octave.info,  Node: Calling Functions,  Next: Arithmetic Ops,  Prev: Index Expressions,  Up: Expressions

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

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

8.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 Function: VAL = max_recursion_depth ()
 -- Built-in Function: OLD_VAL = max_recursion_depth (NEW_VAL)
     Query or set the internal limit on 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.

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

   (1) Some of Octave's functions 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 an error.

   (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

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


File: octave.info,  Node: Comparison Ops,  Next: Boolean Expressions,  Prev: Arithmetic Ops,  Up: Expressions

8.4 Comparison Operators
========================

"Comparison operators" compare numeric values for relationships such as
equality.  They are written using _relational operators_.

   All of Octave's comparison operators return a value of 1 if the
comparison is true, or 0 if it is false.  For matrix values, they all
work on an element-by-element basis.  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'
     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::.

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

     *See also:* isequalwithequalnans.

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

     *See also:* isequal.


File: octave.info,  Node: Boolean Expressions,  Next: Assignment Ops,  Prev: Comparison Ops,  Up: Expressions

8.5 Boolean Expressions
=======================

* Menu:

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


File: octave.info,  Node: Element-by-element Boolean Operators,  Next: Short-circuit Boolean Operators,  Up: Boolean Expressions

8.5.1 Element-by-element Boolean Operators
------------------------------------------

An "element-by-element boolean expression" is a combination of
comparison expressions using the boolean operators "or" (`|'), "and"
(`&'), and "not" (`!'), along with parentheses to control nesting.  The
truth of the boolean expression is computed by combining the truth
values of the corresponding elements of the component expressions.  A
value is considered to be false if it is zero, and true otherwise.

   Element-by-element boolean expressions can be used wherever
comparison expressions can be used.  They can be used in `if' and
`while' statements.  However, 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

8.5.2 Short-circuit Boolean Operators
-------------------------------------

Combined with the implicit conversion to scalar values in `if' and
`while' conditions, Octave's element-by-element boolean operators are
often sufficient for performing most logical operations.  However, it
is sometimes desirable to stop evaluating a boolean expression as soon
as the overall truth value can be determined.  Octave's "short-circuit"
boolean operators work this way.

`BOOLEAN1 && BOOLEAN2'
     The expression BOOLEAN1 is evaluated and converted to a scalar
     using the equivalent of the operation `all (BOOLEAN1(:))'.  If it
     is false, the result of the overall expression is 0.  If it is
     true, the expression BOOLEAN2 is evaluated and converted to a
     scalar using the equivalent of the operation `all (BOOLEAN1(:))'.
     If it is true, the result of the overall expression is 1.
     Otherwise, the result of the overall expression is 0.

     *Warning:* there is one exception to the rule of evaluating `all
     (BOOLEAN1(:))', which is when `boolean1' is the empty matrix. The
     truth value of an empty matrix is always `false' so `[] && true'
     evaluates to `false' even though `all ([])' is `true'.

`BOOLEAN1 || BOOLEAN2'
     The expression BOOLEAN1 is evaluated and converted to a scalar
     using the equivalent of the operation `all (BOOLEAN1(:))'.  If it
     is true, the result of the overall expression is 1.  If it is
     false, the expression BOOLEAN2 is evaluated and converted to a
     scalar using the equivalent of the operation `all (BOOLEAN1(:))'.
     If it is true, the result of the overall expression is 1.
     Otherwise, the result of the overall expression is 0.

     *Warning:* the truth value of an empty matrix is always `false',
     see the previous list item for details.

   The fact that both operands may not be evaluated before determining
the overall truth value of the expression can be important.  For
example, in the expression

     a && b++

the value of the variable B is only incremented if the variable A is
nonzero.

   This can be used to write somewhat more concise code.  For example,
it is possible write

     function f (a, b, c)
       if (nargin > 2 && 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

8.6 Assignment Expressions
==========================

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

     z = 1

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

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

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

(This also illustrates concatenation of strings.)

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

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

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

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

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

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

     a(:, 2) = 5

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

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

     A (3, :) = []

deletes the third row of A, and the assignment

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

deletes the first, third, and fifth columns.

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

     x = y = z = 0

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

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

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

that is exactly equivalent to

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

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

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

is equivalent to

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

The number of values on the left side of the expression can, however,
not exceed the number of values on the right side. For example, the
following will produce an error.

     [a, b, c, d] = [u, s, v] = svd (a)
     -| error: element number 4 undefined in return list
     -| error: evaluating assignment expression near line 8, column 15

   A very common programming pattern is to increment an existing
variable with a given value, like this

     a = a + 2;

This can be written in a clearer and more condensed form using the `+='
operator

     a += 2;

Similar operators also exist for subtraction (`-='), multiplication
(`*='), and division (`/='). An expression of the form

     EXPR1 OP= EXPR2

is evaluated as

     EXPR1 = (EXPR1) OP (EXPR2)

where OP can be either `+', `-', `*', or `/'.  So, the expression

     a *= b+1

is evaluated as

     a = a * (b+1)

and _not_

     a = a * b + 1

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

 -- Built-in Function:  subsasgn (VAL, IDX, RHS)
     Perform the subscripted assignment operation according to the
     subscript specified by IDX.

     The subscript IDX is expected to be a structure array with fields
     `type' and `subs'.  Valid values for `type' are `"()"', `"{}"',
     and `"."'.  The `subs' field may be either `":"' or a cell array
     of index values.

     The following example shows how to set the two first columns of a
     3-by-3 matrix to zero.

          val = magic(3);
          idx.type = "()";
          idx.subs = {":", 1:2};
          subsasgn (val, idx, 0)
               => [ 0   0   6
                    0   0   7
                    0   0   2 ]

     Note that this is the same as writing `val(:,1:2) = 0'.

     *See also:* subsref, substruct.


File: octave.info,  Node: Increment Ops,  Next: Operator Precedence,  Prev: Assignment Ops,  Up: Expressions

8.7 Increment Operators
=======================

_Increment operators_ increase or decrease the value of a variable by
1.  The operator to increment a variable is written as `++'.  It may be
used to increment a variable either before or after taking its value.

   For example, to pre-increment the variable X, you would write `++X'.
This would add one to X and then return the new value of X as the
result of the expression.  It is exactly the same as the expression `X
= X + 1'.

   To post-increment a variable X, you would write `X++'.  This adds
one to the variable X, but returns the value that X had prior to
incrementing it.  For example, if X is equal to 2, the result of the
expression `X++' is 2, and the new value of X is 3.

   For matrix and vector arguments, the increment and decrement
operators work on each element of the operand.

   Here is a list of all the increment and decrement expressions.

`++X'
     This expression increments the variable X.  The value of the
     expression is the _new_ value of X.  It is equivalent to the
     expression `X = X + 1'.

`--X'
     This expression decrements the variable X.  The value of the
     expression is the _new_ value of X.  It is equivalent to the
     expression `X = X - 1'.

`X++'
     This expression causes the variable X to be incremented.  The
     value of the expression is the _old_ value of X.

`X--'
     This expression causes the variable X to be decremented.  The
     value of the expression is the _old_ value of X.


File: octave.info,  Node: Operator Precedence,  Prev: Increment Ops,  Up: Expressions

8.8 Operator Precedence
=======================

"Operator precedence" determines how operators are grouped, when
different operators appear close by in one expression.  For example,
`*' has higher precedence than `+'.  Thus, the expression `a + b * c'
means to multiply `b' and `c', and then add `a' to the product (i.e.,
`a + (b * c)').

   You can overrule the precedence of the operators by using
parentheses.  You can think of the precedence rules as saying where the
parentheses are assumed if you do not write parentheses yourself.  In
fact, it is wise to use parentheses whenever you have an unusual
combination of operators, because other people who read the program may
not remember what the precedence is in this case.  You might forget as
well, and then you too could make a mistake.  Explicit parentheses will
help prevent any such mistake.

   When operators of equal precedence are used together, the leftmost
operator groups first, except for the assignment and exponentiation
operators, which group in the opposite order.  Thus, the expression `a
- b + c' groups as `(a - b) + c', but the expression `a = b = c' groups
as `a = (b = c)'.

   The precedence of prefix unary operators is important when another
operator follows the operand.  For example, `-x^2' means `-(x^2)',
because `-' has lower precedence than `^'.

   Here is a table of the operators in Octave, in order of increasing
precedence.

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

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

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

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

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

`colon'
     `:'.

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

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

`transpose'
     `'', `.''

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

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


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

9 Evaluation
************

Normally, you evaluate expressions simply by typing them at the Octave
prompt, or by asking Octave to interpret commands that you have saved in
a file.

   Sometimes, you may find it necessary to evaluate an expression that
has been computed and stored in a string, which is exactly what the
`eval' lets you do.

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

     The following example makes the variable A with the approximate
     value 3.1416 available.

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

     If an error occurs during the evaluation of TRY the CATCH string
     is evaluated, as the following example shows.

          eval ('error ("This is a bad example");',
                'printf ("This error occurred:\n%s", lasterr ());');
               -| This error occurred:
                  error: This is a bad example

* Menu:

* Calling a Function by its Name::
* Evaluation in a Different Context::


File: octave.info,  Node: Calling a Function by its Name,  Next: Evaluation in a Different Context,  Up: Evaluation

9.1 Calling a Function by its Name
==================================

The `feval' function allows you to call a function from a string
containing its name. This is useful when writing a function that need to
call user-supplied functions. The `feval' function takes the name of
the function to call as its first argument, and the remaining arguments
are given to the function.

   The following example is a simple-minded function using `feval' that
finds the root of a user-supplied function of one variable using
Newton's method.

     function result = newtroot (fname, x)

     # usage: newtroot (fname, x)
     #
     #   fname : a string naming a function f(x).
     #   x     : initial guess

       delta = tol = sqrt (eps);
       maxit = 200;
       fx = feval (fname, x);
       for i = 1:maxit
         if (abs (fx) < tol)
           result = x;
           return;
         else
           fx_new = feval (fname, x + delta);
           deriv = (fx_new - fx) / delta;
           x = x - fx / deriv;
           fx = fx_new;
         endif
       endfor

       result = x;

     endfunction

   Note that this is only meant to be an example of calling
user-supplied functions and should not be taken too seriously.  In
addition to using a more robust algorithm, any serious code would check
the number and type of all the arguments, ensure that the supplied
function really was a function, etc.  *Note Predicates for Numeric
Objects::, for example, for a list of predicates for numeric objects,
and see *note Status of Variables::, for a description of the `exist'
function.

 -- Built-in Function:  feval (NAME, ...)
     Evaluate the function named NAME.  Any arguments after the first
     are passed on to the named function.  For example,

          feval ("acos", -1)
               => 3.1416

     calls the function `acos' with the argument `-1'.

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

   A similar function `run' exists for calling user script files, that
are not necessarily on the user path

 -- Function File:  run (F)
 -- Command:  run F
     Run scripts in the current workspace that are not necessarily on
     the path. If F is the script to run, including its path, then `run'
     change the directory to the directory where F is found. `run' then
     executes the script, and returns to the original directory.

     *See also:* system.


File: octave.info,  Node: Evaluation in a Different Context,  Prev: Calling a Function by its Name,  Up: Evaluation

9.2 Evaluation in a Different Context
=====================================

Before you evaluate an expression you need to substitute the values of
the variables used in the expression.  These are stored in the symbol
table.  Whenever the interpreter starts a new function it saves the
current symbol table and creates a new one, initializing it with the
list of function parameters and a couple of predefined variables such
as `nargin'.  Expressions inside the function use the new symbol table.

   Sometimes you want to write a function so that when you call it, it
modifies variables in your own context.  This allows you to use a
pass-by-name style of function, which is similar to using a pointer in
programming languages such as C.

   Consider how you might write `save' and `load' as m-files.  For
example,

     function create_data
       x = linspace (0, 10, 10);
       y = sin (x);
       save mydata x y
     endfunction

   With `evalin', you could write save as follows:

     function save (file, name1, name2)
       f = open_save_file (file);
       save_var(f, name1, evalin ("caller", name1));
       save_var(f, name2, evalin ("caller", name2));
     endfunction

Here, `caller' is the `create_data' function and `name1' is the string
`"x"', which evaluates simply as the value of `x'.

   You later want to load the values back from `mydata' in a different
context:

     function process_data
       load mydata
       ... do work ...
     endfunction

With `assignin', you could write `load' as follows:

     function load (file)
       f = open_load_file (file);
       [name, val] = load_var (f);
       assignin ("caller", name, val);
       [name, val] = load_var (f);
       assignin ("caller", name, val);
     endfunction

Here, `caller' is the `process_data' function.

   You can set and use variables at the command prompt using the
context `base' rather than `caller'.

   These functions are rarely used in practice.  One example is the
`fail (`code', `pattern')' function which evaluates `code' in the
caller's context and checks that the error message it produces matches
the given pattern.  Other examples such as `save' and `load' are
written in C++ where all octave variables are in the `caller' context
and `evalin' is not needed.

 -- Built-in Function:  evalin (CONTEXT, TRY, CATCH)
     Like `eval', except that the expressions are evaluated in the
     context CONTEXT, which may be either `"caller"' or `"base"'.

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


File: octave.info,  Node: Statements,  Next: Functions and Scripts,  Prev: Evaluation,  Up: Top

10 Statements
*************

Statements may be a simple constant expression or a complicated list of
nested loops and conditional statements.

   "Control statements" such as `if', `while', and so on control the
flow of execution in Octave programs.  All the control statements start
with special keywords such as `if' and `while', to distinguish them
from simple expressions.  Many control statements contain other
statements; for example, the `if' statement contains another statement
which may or may not be executed.

   Each control statement has a corresponding "end" statement that
marks the end of the end of the control statement.  For example, the
keyword `endif' marks the end of an `if' statement, and `endwhile'
marks the end of a `while' statement.  You can use the keyword `end'
anywhere a more specific end keyword is expected, but using the more
specific keywords is preferred because if you use them, Octave is able
to provide better diagnostics for mismatched or missing end tokens.

   The list of statements contained between keywords like `if' or
`while' and the corresponding end statement is called the "body" of a
control statement.

* Menu:

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


File: octave.info,  Node: The if Statement,  Next: The switch Statement,  Up: Statements

10.1 The `if' Statement
=======================

The `if' statement is Octave's decision-making statement.  There are
three basic forms of an `if' statement.  In its simplest form, it looks
like this:

     if (CONDITION)
       THEN-BODY
     endif

CONDITION is an expression that controls what the rest of the statement
will do.  The THEN-BODY is executed only if CONDITION is true.

   The condition in an `if' statement is considered true if its value
is non-zero, and false if its value is zero.  If the value of the
conditional expression in an `if' statement is a vector or a matrix, it
is considered true only if it is non-empty and _all_ of the elements
are non-zero.

   The second form of an if statement looks like this:

     if (CONDITION)
       THEN-BODY
     else
       ELSE-BODY
     endif

If CONDITION is true, THEN-BODY is executed; otherwise, ELSE-BODY is
executed.

   Here is an example:

     if (rem (x, 2) == 0)
       printf ("x is even\n");
     else
       printf ("x is odd\n");
     endif

   In this example, if the expression `rem (x, 2) == 0' is true (that
is, the value of `x' is divisible by 2), then the first `printf'
statement is evaluated, otherwise the second `printf' statement is
evaluated.

   The third and most general form of the `if' statement allows
multiple decisions to be combined in a single statement.  It looks like
this:

     if (CONDITION)
       THEN-BODY
     elseif (CONDITION)
       ELSEIF-BODY
     else
       ELSE-BODY
     endif

Any number of `elseif' clauses may appear.  Each condition is tested in
turn, and if one is found to be true, its corresponding BODY is
executed.  If none of the conditions are true and the `else' clause is
present, its body is executed.  Only one `else' clause may appear, and
it must be the last part of the statement.

   In the following example, if the first condition is true (that is,
the value of `x' is divisible by 2), then the first `printf' statement
is executed.  If it is false, then the second condition is tested, and
if it is true (that is, the value of `x' is divisible by 3), then the
second `printf' statement is executed.  Otherwise, the third `printf'
statement is performed.

     if (rem (x, 2) == 0)
       printf ("x is even\n");
     elseif (rem (x, 3) == 0)
       printf ("x is odd and divisible by 3\n");
     else
       printf ("x is odd\n");
     endif

   Note that the `elseif' keyword must not be spelled `else if', as is
allowed in Fortran.  If it is, the space between the `else' and `if'
will tell Octave to treat this as a new `if' statement within another
`if' statement's `else' clause.  For example, if you write

     if (C1)
       BODY-1
     else if (C2)
       BODY-2
     endif

Octave will expect additional input to complete the first `if'
statement.  If you are using Octave interactively, it will continue to
prompt you for additional input.  If Octave is reading this input from a
file, it may complain about missing or mismatched `end' statements, or,
if you have not used the more specific `end' statements (`endif',
`endfor', etc.), it may simply produce incorrect results, without
producing any warning messages.

   It is much easier to see the error if we rewrite the statements above
like this,

     if (C1)
       BODY-1
     else
       if (C2)
         BODY-2
       endif

using the indentation to show how Octave groups the statements.  *Note
Functions and Scripts::.


File: octave.info,  Node: The switch Statement,  Next: The while Statement,  Prev: The if Statement,  Up: Statements

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

It is very common to take different actions depending on the value of
one variable. This is possible using the `if' statement in the
following way

     if (X == 1)
       do_something ();
     elseif (X == 2)
       do_something_else ();
     else
       do_something_completely_different ();
     endif

This kind of code can however be very cumbersome to both write and
maintain. To overcome this problem Octave supports the `switch'
statement. Using this statement, the above example becomes

     switch (X)
       case 1
         do_something ();
       case 2
         do_something_else ();
       otherwise
         do_something_completely_different ();
     endswitch

This code makes the repetitive structure of the problem more explicit,
making the code easier to read, and hence maintain. Also, if the
variable `X' should change it's name, only one line would need changing
compared to one line per case when `if' statements are used.

   The general form of the `switch' statement is

     switch EXPRESSION
       case LABEL
         COMMAND_LIST
       case LABEL
         COMMAND_LIST
       ...

       otherwise
         COMMAND_LIST
     endswitch

where LABEL can be any expression. However, duplicate LABEL values are
not detected, and only the COMMAND_LIST corresponding to the first
match will be executed. For the `switch' statement to be meaningful at
least one `case LABEL COMMAND_LIST' clause must be present, while the
`otherwise COMMAND_LIST' clause is optional.

   If LABEL is a cell array the corresponding COMMAND_LIST is executed
if _any_ of the elements of the cell array match EXPRESSION. As an
example, the following program will print `Variable is either 6 or 7'.

     A = 7;
     switch A
       case { 6, 7 }
         printf ("variable is either 6 or 7\n");
       otherwise
         printf ("variable is neither 6 nor 7\n");
     endswitch

   As with all other specific `end' keywords, `endswitch' may be
replaced by `end', but you can get better diagnostics if you use the
specific forms.

   One advantage of using the `switch' statement compared to using `if'
statements is that the LABELs can be strings. If an `if' statement is
used it is _not_ possible to write

     if (X == "a string") # This is NOT valid

since a character-to-character comparison between `X' and the string
will be made instead of evaluating if the strings are equal.  This
special-case is handled by the `switch' statement, and it is possible
to write programs that look like this

     switch (X)
       case "a string"
         do_something
       ...
     endswitch

* Menu:

* Notes for the C programmer::


File: octave.info,  Node: Notes for the C programmer,  Up: The switch Statement

10.2.1 Notes for the C programmer
---------------------------------

The `switch' statement is also available in the widely used C
programming language. There are, however, some differences between the
statement in Octave and C

   * Cases are exclusive, so they don't `fall through' as do the cases
     in the `switch' statement of the C language.

   * The COMMAND_LIST elements are not optional.  Making the list
     optional would have meant requiring a separator between the label
     and the command list.  Otherwise, things like

          switch (foo)
            case (1) -2
            ...

     would produce surprising results, as would

          switch (foo)
            case (1)
            case (2)
              doit ();
            ...

     particularly for C programmers. If `doit()' should be executed if
     FOO is either `1' or `2', the above code should be written with a
     cell array like this

          switch (foo)
            case { 1, 2 }
              doit ();
            ...


File: octave.info,  Node: The while Statement,  Next: The do-until Statement,  Prev: The switch Statement,  Up: Statements

10.3 The `while' Statement
==========================

In programming, a "loop" means a part of a program that is (or at least
can be) executed two or more times in succession.

   The `while' statement is the simplest looping statement in Octave.
It repeatedly executes a statement as long as a condition is true.  As
with the condition in an `if' statement, the condition in a `while'
statement is considered true if its value is non-zero, and false if its
value is zero.  If the value of the conditional expression in a `while'
statement is a vector or a matrix, it is considered true only if it is
non-empty and _all_ of the elements are non-zero.

   Octave's `while' statement looks like this:

     while (CONDITION)
       BODY
     endwhile

Here BODY is a statement or list of statements that we call the "body"
of the loop, and CONDITION is an expression that controls how long the
loop keeps running.

   The first thing the `while' statement does is test CONDITION.  If
CONDITION is true, it executes the statement BODY.  After BODY has been
executed, CONDITION is tested again, and if it is still true, BODY is
executed again.  This process repeats until CONDITION is no longer
true.  If CONDITION is initially false, the body of the loop is never
executed.

   This example creates a variable `fib' that contains the first ten
elements of the Fibonacci sequence.

     fib = ones (1, 10);
     i = 3;
     while (i <= 10)
       fib (i) = fib (i-1) + fib (i-2);
       i++;
     endwhile

Here the body of the loop contains two statements.

   The loop works like this: first, the value of `i' is set to 3.
Then, the `while' tests whether `i' is less than or equal to 10.  This
is the case when `i' equals 3, so the value of the `i'-th element of
`fib' is set to the sum of the previous two values in the sequence.
Then the `i++' increments the value of `i' and the loop repeats.  The
loop terminates when `i' reaches 11.

   A newline is not required between the condition and the body; but
using one makes the program clearer unless the body is very simple.


File: octave.info,  Node: The do-until Statement,  Next: The for Statement,  Prev: The while Statement,  Up: Statements

10.4 The `do-until' Statement
=============================

The `do-until' statement is similar to the `while' statement, except
that it repeatedly executes a statement until a condition becomes true,
and the test of the condition is at the end of the loop, so the body of
the loop is always executed at least once.  As with the condition in an
`if' statement, the condition in a `do-until' statement is considered
true if its value is non-zero, and false if its value is zero.  If the
value of the conditional expression in a `do-until' statement is a
vector or a matrix, it is considered true only if it is non-empty and
_all_ of the elements are non-zero.

   Octave's `do-until' statement looks like this:

     do
       BODY
     until (CONDITION)

Here BODY is a statement or list of statements that we call the "body"
of the loop, and CONDITION is an expression that controls how long the
loop keeps running.

   This example creates a variable `fib' that contains the first ten
elements of the Fibonacci sequence.

     fib = ones (1, 10);
     i = 2;
     do
       i++;
       fib (i) = fib (i-1) + fib (i-2);
     until (i == 10)

   A newline is not required between the `do' keyword and the body; but
using one makes the program clearer unless the body is very simple.


File: octave.info,  Node: The for Statement,  Next: The break Statement,  Prev: The do-until Statement,  Up: Statements

10.5 The `for' Statement
========================

The `for' statement makes it more convenient to count iterations of a
loop.  The general form of the `for' statement looks like this:

     for VAR = EXPRESSION
       BODY
     endfor

where BODY stands for any statement or list of statements, EXPRESSION
is any valid expression, and VAR may take several forms.  Usually it is
a simple variable name or an indexed variable.  If the value of
EXPRESSION is a structure, VAR may also be a vector with two elements.
*Note Looping Over Structure Elements::, below.

   The assignment expression in the `for' statement works a bit
differently than Octave's normal assignment statement.  Instead of
assigning the complete result of the expression, it assigns each column
of the expression to VAR in turn.  If EXPRESSION is a range, a row
vector, or a scalar, the value of VAR will be a scalar each time the
loop body is executed.  If VAR is a column vector or a matrix, VAR will
be a column vector each time the loop body is executed.

   The following example shows another way to create a vector containing
the first ten elements of the Fibonacci sequence, this time using the
`for' statement:

     fib = ones (1, 10);
     for i = 3:10
       fib (i) = fib (i-1) + fib (i-2);
     endfor

This code works by first evaluating the expression `3:10', to produce a
range of values from 3 to 10 inclusive.  Then the variable `i' is
assigned the first element of the range and the body of the loop is
executed once.  When the end of the loop body is reached, the next
value in the range is assigned to the variable `i', and the loop body
is executed again.  This process continues until there are no more
elements to assign.

   Within Octave is it also possible to iterate over matrices or cell
arrays using the `for' statement. For example consider

     disp("Loop over a matrix")
     for i = [1,3;2,4]
       i
     endfor
     disp("Loop over a cell array")
     for i = {1,"two";"three",4}
       i
     endfor

In this case the variable `i' takes on the value of the columns of the
matrix or cell matrix. So the first loop iterates twice, producing two
column vectors `[1;2]', followed by `[3;4]', and likewise for the loop
over the cell array. This can be extended to loops over
multidimensional arrays. For example

     a = [1,3;2,4]; b = cat(3, a, 2*a);
     for i = c
       i
     endfor

In the above case, the multidimensional matrix C is reshaped to a two
dimensional matrix as `reshape (c, rows(c), prod(size(c)(2:end)))' and
then the same behavior as a loop over a two dimensional matrix is
produced.

   Although it is possible to rewrite all `for' loops as `while' loops,
the Octave language has both statements because often a `for' loop is
both less work to type and more natural to think of.  Counting the
number of iterations is very common in loops and it can be easier to
think of this counting as part of looping rather than as something to
do inside the loop.

* Menu:

* Looping Over Structure Elements::


File: octave.info,  Node: Looping Over Structure Elements,  Up: The for Statement

10.5.1 Looping Over Structure Elements
--------------------------------------

A special form of the `for' statement allows you to loop over all the
elements of a structure:

     for [ VAL, KEY ] = EXPRESSION
       BODY
     endfor

In this form of the `for' statement, the value of EXPRESSION must be a
structure.  If it is, KEY and VAL are set to the name of the element
and the corresponding value in turn, until there are no more elements.
For example,

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

          -| key = a
          -| val = 1
          -| key = b
          -| val =
          -|
          -|   1  2
          -|   3  4
          -|
          -| key = c
          -| val = string

   The elements are not accessed in any particular order.  If you need
to cycle through the list in a particular way, you will have to use the
function `fieldnames' and sort the list yourself.

   The KEY variable may also be omitted.  If it is, the brackets are
also optional.  This is useful for cycling through the values of all the
structure elements when the names of the elements do not need to be
known.


File: octave.info,  Node: The break Statement,  Next: The continue Statement,  Prev: The for Statement,  Up: Statements

10.6 The `break' Statement
==========================

The `break' statement jumps out of the innermost `for' or `while' loop
that encloses it.  The `break' statement may only be used within the
body of a loop.  The following example finds the smallest divisor of a
given integer, and also identifies prime numbers:

     num = 103;
     div = 2;
     while (div*div <= num)
       if (rem (num, div) == 0)
         break;
       endif
       div++;
     endwhile
     if (rem (num, div) == 0)
       printf ("Smallest divisor of %d is %d\n", num, div)
     else
       printf ("%d is prime\n", num);
     endif

   When the remainder is zero in the first `while' statement, Octave
immediately "breaks out" of the loop.  This means that Octave proceeds
immediately to the statement following the loop and continues
processing.  (This is very different from the `exit' statement which
stops the entire Octave program.)

   Here is another program equivalent to the previous one.  It
illustrates how the CONDITION of a `while' statement could just as well
be replaced with a `break' inside an `if':

     num = 103;
     div = 2;
     while (1)
       if (rem (num, div) == 0)
         printf ("Smallest divisor of %d is %d\n", num, div);
         break;
       endif
       div++;
       if (div*div > num)
         printf ("%d is prime\n", num);
         break;
       endif
     endwhile


File: octave.info,  Node: The continue Statement,  Next: The unwind_protect Statement,  Prev: The break Statement,  Up: Statements

10.7 The `continue' Statement
=============================

The `continue' statement, like `break', is used only inside `for' or
`while' loops.  It skips over the rest of the loop body, causing the
next cycle around the loop to begin immediately.  Contrast this with
`break', which jumps out of the loop altogether.  Here is an example:

     # print elements of a vector of random
     # integers that are even.

     # first, create a row vector of 10 random
     # integers with values between 0 and 100:

     vec = round (rand (1, 10) * 100);

     # print what we're interested in:

     for x = vec
       if (rem (x, 2) != 0)
         continue;
       endif
       printf ("%d\n", x);
     endfor

   If one of the elements of VEC is an odd number, this example skips
the print statement for that element, and continues back to the first
statement in the loop.

   This is not a practical example of the `continue' statement, but it
should give you a clear understanding of how it works.  Normally, one
would probably write the loop like this:

     for x = vec
       if (rem (x, 2) == 0)
         printf ("%d\n", x);
       endif
     endfor


File: octave.info,  Node: The unwind_protect Statement,  Next: The try Statement,  Prev: The continue Statement,  Up: Statements

10.8 The `unwind_protect' Statement
===================================

Octave supports a limited form of exception handling modelled after the
unwind-protect form of Lisp.

   The general form of an `unwind_protect' block looks like this:

     unwind_protect
       BODY
     unwind_protect_cleanup
       CLEANUP
     end_unwind_protect

where BODY and CLEANUP are both optional and may contain any Octave
expressions or commands.  The statements in CLEANUP are guaranteed to
be executed regardless of how control exits BODY.

   This is useful to protect temporary changes to global variables from
possible errors.  For example, the following code will always restore
the original value of the global variable `frobnositcate' even if an
error occurs while performing the indexing operation.

     save_frobnosticate = frobnosticate;
     unwind_protect
       frobnosticate = true;
       ...
     unwind_protect_cleanup
       frobnosticate = save_frobnosticate;
     end_unwind_protect

Without `unwind_protect', the value of FROBNOSTICATE would not be
restored if an error occurs while 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

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

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

   The general form of a `try' block looks like this:

     try
       BODY
     catch
       CLEANUP
     end_try_catch

where BODY and CLEANUP are both optional and may contain any Octave
expressions or commands.  The statements in CLEANUP are only executed
if an error occurs in BODY.

   No warnings or error messages are printed while BODY is executing.
If an error does occur during the execution of BODY, CLEANUP can use
the function `lasterr' to access the text of the message that would
have been printed.  This is the same as `eval (TRY, CATCH)' but it is
more efficient since the commands do not need to be parsed each time
the TRY and CATCH statements are evaluated.  *Note Errors and
Warnings::, for more information about the `lasterr' function.


File: octave.info,  Node: Continuation Lines,  Prev: The try Statement,  Up: Statements

10.10 Continuation Lines
========================

In the Octave language, most statements end with a newline character and
you must tell Octave to ignore the newline character in order to
continue a statement from one line to the next.  Lines that end with the
characters `...' or `\' are joined with the following line before they
are divided into tokens by Octave's parser.  For example, the lines

     x = long_variable_name ...
         + longer_variable_name \
         - 42

form a single statement.  The backslash character on the second line
above is interpreted as a continuation character, _not_ as a division
operator.

   For continuation lines that do not occur inside string constants,
whitespace and comments may appear between the continuation marker and
the newline character.  For example, the statement

     x = long_variable_name ...     # comment one
         + longer_variable_name \   # comment two
         - 42                       # last comment

is equivalent to the one shown above.  Inside string constants, the
continuation marker must appear at the end of the line just before the
newline character.

   Input that occurs inside parentheses can be continued to the next
line without having to use a continuation marker.  For example, it is
possible to write statements like

     if (fine_dining_destination == on_a_boat
         || fine_dining_destination == on_a_train)
       seuss (i, will, not, eat, them, sam, i, am, i,
              will, not, eat, green, eggs, and, ham);
     endif

without having to add to the clutter with continuation markers.


File: octave.info,  Node: Functions and Scripts,  Next: Errors and Warnings,  Prev: Statements,  Up: Top

11 Functions and 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::
* Default Arguments::
* Function Files::
* Script Files::
* Function Handles Inline Functions and Anonymous Functions::
* Commands::
* Organization of Functions::


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

11.1 Defining Functions
=======================

In its simplest form, the definition of a function named NAME looks
like this:

     function NAME
       BODY
     endfunction

A valid function name is like a valid variable name: a sequence of
letters, digits and underscores, not starting with a digit.  Functions
share the same pool of names as variables.

   The function BODY consists of Octave statements.  It is the most
important part of the definition, because it says what the function
should actually _do_.

   For example, here is a function that, when executed, will ring the
bell on your terminal (assuming that it is possible to do so):

     function wakeup
       printf ("\a");
     endfunction

   The `printf' statement (*note Input and Output::) simply tells
Octave to print the string `"\a"'.  The special character `\a' stands
for the alert character (ASCII 7).  *Note Strings::.

   Once this function is defined, you can ask Octave to evaluate it by
typing the name of the function.

   Normally, you will want to pass some information to the functions you
define.  The syntax for passing parameters to a function in Octave is

     function NAME (ARG-LIST)
       BODY
     endfunction

where ARG-LIST is a comma-separated list of the function's arguments.
When the function is called, the argument names are used to hold the
argument values given in the call.  The list of arguments may be empty,
in which case this form is equivalent to the one shown above.

   To print a message along with ringing the bell, you might modify the
`wakeup' to look like this:

     function wakeup (message)
       printf ("\a%s\n", message);
     endfunction

   Calling this function using a statement like this

     wakeup ("Rise and shine!");

will cause Octave to ring your terminal's bell and print the message
`Rise and shine!', followed by a newline character (the `\n' in the
first argument to the `printf' statement).

   In most cases, you will also want to get some information back from
the functions you define.  Here is the syntax for writing a function
that returns a single value:

     function RET-VAR = NAME (ARG-LIST)
       BODY
     endfunction

The symbol RET-VAR is the name of the variable that will hold the value
to be returned by the function.  This variable must be defined before
the end of the function body in order for the function to return a
value.

   Variables used in the body of a function are local to the function.
Variables named in ARG-LIST and RET-VAR are also local to the function.
*Note Global Variables::, for information about how to access global
variables inside a function.

   For example, here is a function that computes the average of the
elements of a vector:

     function retval = avg (v)
       retval = sum (v) / length (v);
     endfunction

   If we had written `avg' like this instead,

     function retval = avg (v)
       if (isvector (v))
         retval = sum (v) / length (v);
       endif
     endfunction

and then called the function with a matrix instead of a vector as the
argument, Octave would have printed an error message like this:

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

     *See also:* nargout, varargin, varargout.

 -- Function File:  inputname (N)
     Return the text defining N-th input to the function.

 -- Built-in Function: VAL = silent_functions ()
 -- Built-in Function: OLD_VAL = silent_functions (NEW_VAL)
     Query or set the internal variable that controls whether internal
     output from a function is suppressed.  If this option is disabled,
     Octave will display the results produced by evaluating expressions
     within a function body that are not terminated with a semicolon.


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

11.2 Multiple Return Values
===========================

Unlike many other computer languages, Octave allows you to define
functions that return more than one value.  The syntax for defining
functions that return multiple values is

     function [RET-LIST] = NAME (ARG-LIST)
       BODY
     endfunction

where NAME, ARG-LIST, and BODY have the same meaning as before, and
RET-LIST is a comma-separated list of variable names that will hold the
values returned from the function.  The list of return values must have
at least one element.  If RET-LIST has only one element, this form of
the `function' statement is equivalent to the form described in the
previous section.

   Here is an example of a function that returns two values, the maximum
element of a vector and the index of its first occurrence in the vector.

     function [max, idx] = vmax (v)
       idx = 1;
       max = v (idx);
       for i = 2:length (v)
         if (v (i) > max)
           max = v (i);
           idx = i;
         endif
       endfor
     endfunction

   In this particular case, the two values could have been returned as
elements of a single array, but that is not always possible or
convenient.  The values to be returned may not have compatible
dimensions, and it is often desirable to give the individual return
values distinct names.

   In addition to setting `nargin' each time a function is called,
Octave also automatically initializes `nargout' to the number of values
that are expected to be returned.  This allows you to write functions
that behave differently depending on the number of values that the user
of the function has requested.  The implicit assignment to the built-in
variable `ans' does not figure in the count of output arguments, so the
value of `nargout' may be zero.

   The `svd' and `lu' functions are examples of built-in functions that
behave differently depending on the value of `nargout'.

   It is possible to write functions that only set some return values.
For example, calling the function

     function [x, y, z] = f ()
       x = 1;
       z = 2;
     endfunction

as

     [a, b, c] = f ()

produces:

     a = 1

     b = [](0x0)

     c = 2

along with a warning.

 -- Built-in Function:  nargout ()
 -- Built-in Function:  nargout (FCN_NAME)
     Within a function, return the number of values the caller expects
     to receive.  If called with the optional argument FCN_NAME, return
     the maximum number of values the named function can produce, or -1
     if the function can produce a variable number of values.

     For example,

          f ()

     will cause `nargout' to return 0 inside the function `f' and

          [s, t] = f ()

     will cause `nargout' to return 2 inside the function `f'.

     At the top level, `nargout' is undefined.

     *See also:* nargin, varargin, varargout.

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

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

Sometimes the number of input arguments is not known when the function
is defined.  As an example think of a function that returns the smallest
of all its input arguments.  For example,

     a = smallest (1, 2, 3);
     b = smallest (1, 2, 3, 4);

In this example both `a' and `b' would be 1.  One way to write the
`smallest' function is

     function val = smallest (arg1, arg2, arg3, arg4, arg5)
       BODY
     endfunction

and then use the value of `nargin' to determine which of the input
arguments should be considered. The problem with this approach is that
it can only handle a limited number of input arguments.

   Octave supports the `varargin' keyword for handling a variable
number of input arguments. Using `varargin' the function looks like this

     function val = smallest (varargin)
       BODY
     endfunction

In the function body the input arguments can be accessed through the
variable `varargin'. This variable is a cell array containing all the
input arguments. *Note Cell Arrays::, for details on working with cell
arrays. The `smallest' function can now be defined like this

     function val = smallest (varargin)
       val = min ([varargin{:}]);
     endfunction

This implementation handles any number of input arguments, but it's also
a very simple solution to the problem.

   A slightly more complex example of `varargin' is a function
`print_arguments' that prints all input arguments.  Such a function can
be defined like this

     function print_arguments (varargin)
       for i = 1:length (varargin)
         printf ("Input argument %d: ", i);
         disp (varargin{i});
       endfor
     endfunction

This function produces output like this

     print_arguments (1, "two", 3);
          -| Input argument 1:  1
          -| Input argument 2: two
          -| Input argument 3:  3

 -- Function File: [REG, PROP] = parseparams (PARAMS)
     Return in REG the cell elements of PARAM up to the first string
     element and in PROP all remaining elements beginning with the
     first string element.  For example

          [reg, prop] = parseparams ({1, 2, "linewidth", 10})
          reg =
          {
            [1,1] = 1
            [1,2] = 2
          }
          prop =
          {
            [1,1] = linewidth
            [1,2] = 10
          }

     The parseparams function may be used to separate 'regular'
     arguments and additional arguments given as property/value pairs of
     the VARARGIN cell array.

     *See also:* varargin.


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

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

It is possible to return a variable number of output arguments from a
function using a syntax that's similar to the one used with the
`varargin' keyword.  To let a function return a variable number of
output arguments the `varargout' keyword is used.  As with `varargin'
`varargout' is a cell array that will contain the requested output
arguments.

   As an example the following function sets the first output argument
to 1, the second to 2, and so on.

     function varargout = one_to_n ()
       for i = 1:nargout
         varargout{i} = i;
       endfor
     endfunction

When called this function returns values like this

     [a, b, c] = one_to_n ()
          => a =  1
          => b =  2
          => c =  3

 -- Function File: [R1, R2, ..., RN] = deal (A)
 -- Function File: [R1, R2, ..., RN] = deal (A1, A2, ..., AN)
     Copy the input parameters into the corresponding output parameters.
     If only one input parameter is supplied, its value is copied to
     each of the outputs.

     For example,

          [a, b, c] = deal (x, y, z);

     is equivalent to

          a = x;
          b = y;
          c = z;

     and

          [a, b, c] = deal (x);

     is equivalent to

          a = b = c = x;


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

11.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: Default Arguments,  Next: Function Files,  Prev: Returning From a Function,  Up: Functions and Scripts

11.6 Default Arguments
======================

Since Octave supports variable number of input arguments, it is very
useful to assign default values to some input arguments. When an input
argument is declared in the argument list it is possible to assign a
default value to the argument like this

     function NAME (ARG1 = VAL1, ...)
       BODY
     endfunction

If no value is assigned to ARG1 by the user, it will have the value
VAL1.

   As an example, the following function implements a variant of the
classic "Hello, World" program.
     function hello (who = "World")
       printf ("Hello, %s!\n", who);
     endfunction

When called without an input argument the function prints the following
     hello ();
          -| Hello, World!

and when it's called with an input argument it prints the following
     hello ("Beautiful World of Free Software");
          -| Hello, Beautiful World of Free Software!

   Sometimes it is useful to explicitly tell Octave to use the default
value of an input argument.  This can be done writing a `:' as the value
of the input argument when calling the function.
     hello (:);
          -| Hello, World!


File: octave.info,  Node: Function Files,  Next: Script Files,  Prev: Default Arguments,  Up: Functions and Scripts

11.7 Function Files
===================

Except for simple one-shot programs, it is not practical to have to
define all the functions you need each time you need them.  Instead, you
will normally want to save them in a file so that you can easily edit
them, and save them for use at a later time.

   Octave does not require you to load function definitions from files
before using them.  You simply need to put the function definitions in a
place where Octave can find them.

   When Octave encounters an identifier that is undefined, it first
looks for variables or functions that are already compiled and currently
listed in its symbol table.  If it fails to find a definition there, it
searches a list of directories (the "path") for files ending in `.m'
that have the same base name as the undefined identifier.(1)  Once
Octave finds a file with a name that matches, the contents of the file
are read.  If it defines a _single_ function, it is compiled and
executed.  *Note Script Files::, for more information about how you can
define more than one function in a single file.

   When Octave defines a function from a function file, it saves the
full name of the file it read and the time stamp on the file.  If the
time stamp on the file changes, Octave may reload the file.  When
Octave is running interactively, time stamp checking normally happens
at most once each time Octave prints the prompt.  Searching for new
function definitions also occurs if the current working directory
changes.

   Checking the time stamp allows you to edit the definition of a
function while Octave is running, and automatically use the new function
definition without having to restart your Octave session.

   To avoid degrading performance unnecessarily by checking the time
stamps on functions that are not likely to change, Octave assumes that
function files in the directory tree
`OCTAVE-HOME/share/octave/VERSION/m' will not change, so it doesn't
have to check their time stamps every time the functions defined in
those files are used.  This is normally a very good assumption and
provides a significant improvement in performance for the function
files that are distributed with Octave.

   If you know that your own function files will not change while you
are running Octave, you can improve performance by calling
`ignore_function_time_stamp ("all")', so that Octave will ignore the
time stamps for all function files.  Passing `"system"' to this
function resets the default behavior.

 -- Built-in Function:  mfilename ()
 -- Built-in Function:  mfilename (`"fullpath"')
 -- Built-in Function:  mfilename (`"fullpathext"')
     Return the name of the currently executing file.  At the top-level,
     return the empty string.  Given the argument `"fullpath"', include
     the directory part of the file name, but not the extension.  Given
     the argument `"fullpathext"', include the directory part of the
     file name and the extension.

 -- Built-in Function: VAL = ignore_function_time_stamp ()
 -- Built-in Function: OLD_VAL = ignore_function_time_stamp (NEW_VAL)
     Query or set the internal variable that controls whether Octave
     checks the time stamp on files each time it looks up functions
     defined in function files.  If the internal variable is set to
     `"system"', Octave will not automatically recompile function files
     in subdirectories of `OCTAVE-HOME/lib/VERSION' if they have
     changed since they were last compiled, but will recompile other
     function files in the search path if they change.  If set to
     `"all"', Octave will not recompile any function files unless their
     definitions are removed with `clear'.  If set to "none", Octave
     will always check time stamps on files to determine whether
     functions defined in function files need to be recompiled.

* Menu:

* Manipulating the load path::
* Subfunctions::
* Overloading and Autoloading::
* Function Locking::

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

   (1) The `.m' suffix was chosen for compatibility with MATLAB.


File: octave.info,  Node: Manipulating the load path,  Next: Subfunctions,  Up: Function Files

11.7.1 Manipulating the load path
---------------------------------

When a function is called Octave searches a list of directories for a
file that contains the function declaration. This list of directories
is known as the load path. By default the load path contains a list of
directories distributed with Octave plus the current working directory.
To see your current load path call the `path' function without any
input or output arguments.

   It is possible to add or remove directories to or from the load path
using the `addpath' and `rmpath'. As an example, the following code
adds `~/Octave' to the load path.

     addpath("~/Octave")

After this the directory `~/Octave' will be searched for functions.

 -- Built-in Function:  addpath (DIR1, ...)
 -- Built-in Function:  addpath (DIR1, ..., OPTION)
     Add DIR1, ... to the current function search path.  If OPTION is
     `"-begin"' or 0 (the default), prepend the directory name to the
     current path.  If OPTION is `"-end"' or 1, append the directory
     name to the current path.  Directories added to the path must
     exist.

     *See also:* path, rmpath, genpath, pathdef, savepath, pathsep.

 -- Built-in Function:  genpath (DIR)
     Return a path constructed from DIR and all its subdiretories.

 -- Built-in Function:  rmpath (DIR1, ...)
     Remove DIR1, ... from the current function search path.


     *See also:* path, addpath, genpath, pathdef, savepath, pathsep.

 -- Function File:  savepath (FILE)
     Save the current function search path to FILE.  If FILE is
     omitted, `~/.octaverc' is used.  If successful, `savepath' returns
     0.

     *See also:* path, addpath, rmpath, genpath, pathdef, pathsep.

 -- Built-in Function:  path (...)
     Modify or display Octave's load path.

     If NARGIN and NARGOUT are zero, display the elements of Octave's
     load path in an easy to read format.

     If NARGIN is zero and nargout is greater than zero, return the
     current load path.

     If NARGIN is greater than zero, concatenate the arguments,
     separating them with `pathsep()'.  Set the internal search path to
     the result and return it.

     No checks are made for duplicate elements.

     *See also:* addpath, rmpath, genpath, pathdef, savepath, pathsep.

 -- Built-in Function: VAL = pathdef ()
     Return the default list of directories in which to search for
     function files.

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

 -- Built-in Function:  pathsep ()
     Return the system-dependent character used to separate directories
     in a path.

     *See also:* filesep, dir, ls.

 -- Built-in Function:  rehash ()
     Reinitialize Octave's load path directory cache.

 -- Built-in Function:  file_in_loadpath (FILE)
 -- Built-in Function:  file_in_loadpath (FILE, "all")
     Return the absolute name of FILE if it can be found in the list of
     directories specified by `path'.  If no file is found, return an
     empty matrix.

     If the first argument is a cell array of strings, search each
     directory of the loadpath for element of the cell array and return
     the first that matches.

     If the second optional argument `"all"' is supplied, return a cell
     array containing the list of all files that have the same name in
     the path.  If no files are found, return an empty cell array.

     *See also:* file_in_path, path.


File: octave.info,  Node: Subfunctions,  Next: Overloading and Autoloading,  Prev: Manipulating the load path,  Up: Function Files

11.7.2 Subfunctions
-------------------

A function file may contain secondary functions called "subfunctions".
These secondary functions are only visible to the other functions in
the same function file.  For example, a file `f.m' containing

     function f ()
       printf ("in f, calling g\n");
       g ()
     endfunction
     function g ()
       printf ("in g, calling h\n");
       h ()
     endfunction
     function h ()
       printf ("in h\n")
     endfunction

defines a main function `f' and two subfunctions.  The subfunctions `g'
and `h' may only be called from the main function `f' or from the other
subfunctions, but not from outside the file `f.m'.


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

11.7.3 Overloading and Autoloading
----------------------------------

The `dispatch' function can be used to alias one function name to
another. It can be used to alias all calls to a particular function name
to another function, or the alias can be limited to only a particular
variable type. Consider the example

     function y = spsin (x)
       printf ("Calling spsin\n");
       fflush(stdout);
       y = spfun ("sin", x);
     endfunction

     dispatch ("sin", "spsin", "sparse matrix");
     y0 = sin(eye(3));
     y1 = sin(speye(3));

Which aliases the `spsin' to `sin', but only for real sparse matrices.
Note that the builtin `sin' already  correctly treats sparse matrices
and so this example is only illustrative.

 -- Loadable Function:  dispatch (F, R, TYPE)
     Replace the function F with a dispatch so that function R is
     called when F is called with the first argument of the named TYPE.
     If the type is ANY then call R if no other type matches.  The
     original function F is accessible using `builtin (F, ...)'.

     If R is omitted, clear dispatch function associated with TYPE.

     If both R and TYPE are omitted, list dispatch functions for F.

     *See also:* builtin.

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

     *See also:* dispatch.

   A single dynamically linked file might define several functions.
However, as Octave searches for functions based on the functions
filename, Octave needs a manner in which to find each of the functions
in the dynamically linked file. On operating systems that support
symbolic links, it is possible to create a symbolic link to the
original file for each of the functions which it contains.

   However, there is at least one well known operating system that
doesn't support symbolic links. Making copies of the original file for
each of the functions is also possible, but is undesirable as it
multiples the amount of disk space used by Octave. Instead Octave
supplies the `autoload' function, that permits the user to define in
which file a certain function will be found.

 -- Built-in Function:  autoload (FUNCTION, FILE)
     Define FUNCTION to autoload from FILE.

     The second argument, FILE, should be an absolute file name or a
     file name in the same directory as the function or script from
     which the autoload command was run. FILE should not depend on the
     Octave load path.

     Normally, calls to `autoload' appear in PKG_ADD script files that
     are evaluated when a directory is added to the Octave's load path.
     To avoid having to hardcode directory names in FILE, if FILE is in
     the same directory as the PKG_ADD script then

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

     will load the function `foo' from the file `bar.oct'. The above
     when `bar.oct' is not in the same directory or uses like

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

     are strongly discouraged, as their behavior might be unpredictable.

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

     *See also:* PKG_ADD.


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

11.7.4 Function Locking
-----------------------

It is sometime desirable to lock a function into memory with the
`mlock' function. This is typically used for dynamically linked
functions in Oct-files or mex-files that contain some initialization,
and it is desirable that calling `clear' does not remove this
initialization.

   As an example,

     mlock ("my_function");

prevents `my_function' from being removed from memory, even if `clear'
is called.  It is possible to determine if a function is locked into
memory with the `mislocked', and to unlock a function with `munlock',
which the following illustrates.

     mlock ("my_function");
     mislocked ("my_function")
     => ans = 1
     munlock ("my_function");
     mislocked ("my_function")
     => ans = 0

   A common use of `mlock' is to prevent persistent variables from
being removed from memory, as the following example shows.

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

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

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

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

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

   `mlock' might equally be used to prevent changes to a function from
having effect in Octave, though a similar effect can be had with the
`ignore_function_time_stamp' function.

 -- Built-in Function:  mlock (NAME)
     Lock the named function into memory.  If no function is named then
     lock in the current function.

     *See also:* munlock, mislocked, persistent.

 -- Built-in Function:  munlock (FCN)
     Unlock the named function.  If no function is named then unlock
     the current function.

     *See also:* mlock, mislocked, persistent.

 -- Built-in Function:  mislocked (FCN)
     Return true if the named function is locked.  If no function is
     named then return true if the current function is locked.

     *See also:* mlock, munlock, persistent.


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

11.8 Script Files
=================

A script file is a file containing (almost) any sequence of Octave
commands.  It is read and evaluated just as if you had typed each
command at the Octave prompt, and provides a convenient way to perform a
sequence of commands that do not logically belong inside a function.

   Unlike a function file, a script file must _not_ begin with the
keyword `function'.  If it does, Octave will assume that it is a
function file, and that it defines a single function that should be
evaluated as soon as it is defined.

   A script file also differs from a function file in that the variables
named in a script file are not local variables, but are in the same
scope as the other variables that are visible on the command line.

   Even though a script file may not begin with the `function' keyword,
it is possible to define more than one function in a single script file
and load (but not execute) all of them at once.  To do this, the first
token in the file (ignoring comments and other white space) must be
something other than `function'.  If you have no other statements to
evaluate, you can use a statement that has no effect, like this:

     # Prevent Octave from thinking that this
     # is a function file:

     1;

     # Define function one:

     function one ()
       ...

   To have Octave read and compile these functions into an internal
form, you need to make sure that the file is in Octave's load path
(accessible through the `path' function), then simply type the base
name of the file that contains the commands.  (Octave uses the same
rules to search for script files as it does to search for function
files.)

   If the first token in a file (ignoring comments) is `function',
Octave will compile the function and try to execute it, printing a
message warning about any non-whitespace characters that appear after
the function definition.

   Note that Octave does not try to look up the definition of any
identifier until it needs to evaluate it.  This means that Octave will
compile the following statements if they appear in a script file, or
are typed at the command line,

     # not a function file:
     1;
     function foo ()
       do_something ();
     endfunction
     function do_something ()
       do_something_else ();
     endfunction

even though the function `do_something' is not defined before it is
referenced in the function `foo'.  This is not an error because Octave
does not need to resolve all symbols that are referenced by a function
until the function is actually evaluated.

   Since Octave doesn't look for definitions until they are needed, the
following code will always print `bar = 3' whether it is typed directly
on the command line, read from a script file, or is part of a function
body, even if there is a function or script file called `bar.m' in
Octave's path.

     eval ("bar = 3");
     bar

   Code like this appearing within a function body could fool Octave if
definitions were resolved as the function was being compiled.  It would
be virtually impossible to make Octave clever enough to evaluate this
code in a consistent fashion.  The parser would have to be able to
perform the call to `eval' at compile time, and that would be
impossible unless all the references in the string to be evaluated could
also be resolved, and requiring that would be too restrictive (the
string might come from user input, or depend on things that are not
known until the function is evaluated).

   Although Octave normally executes commands from script files that
have the name `FILE.m', you can use the function `source' to execute
commands from any file.

 -- Built-in Function:  source (FILE)
     Parse and execute the contents of FILE.  This is equivalent to
     executing commands from a script file, but without requiring the
     file to be named `FILE.m'.


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

11.9 Function Handles, Inline Functions, and Anonymous Functions
================================================================

It can be very convenient store a function in a variable so that it can
be passed to a different function. For example, a function that
performs numerical minimisation needs access to the function that
should be minimised.

* Menu:

* Function Handles::
* Anonymous Functions::
* Inline Functions::


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

11.9.1 Function Handles
-----------------------

A function handle is a pointer to another function and is defined with
the syntax

     @FUNCTION-NAME

For example

     f = @sin;

Creates a function handle called `f' that refers to the function `sin'.

   Function handles are used to call other functions indirectly, or to
pass a function as an argument to another function like `quad' or
`fsolve'.  For example

     f = @sin;
     quad (f, 0, pi)
         => 2

   You may use `feval' to call a function using function handle, or
simply write the name of the function handle followed by an argument
list.  If there are no arguments, you must use an empty argument list
`()'.  For example

     f = @sin;
     feval (f, pi/4)
         => 0.70711
     f (pi/4)
         => 0.70711

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

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

 -- Built-in Function:  str2func (FCN_NAME)
     Return a function handle constructed from the string FCN_NAME.


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

11.9.2 Anonymous Functions
--------------------------

Anonymous functions are defined using the syntax

     @(ARGUMENT-LIST) EXPRESSION

Any variables that are not found in the argument list are inherited from
the enclosing scope.  Anonymous functions are useful for creating simple
unnamed functions from expressions or for wrapping calls to other
functions to adapt them for use by functions like `quad'.  For example,

     f = @(x) x.^2;
     quad (f, 0, 10)
         => 333.33

creates a simple unnamed function from the expression `x.^2' and passes
it to `quad',

     quad (@(x) sin (x), 0, pi)
         => 2

wraps another function, and

     a = 1;
     b = 2;
     quad (@(x) betainc (x, a, b), 0, 0.4)
         => 0.13867

adapts a function with several parameters to the form required by
`quad'.  In this example, the values of A and B that are passed to
`betainc' are inherited from the current environment.


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

11.9.3 Inline Functions
-----------------------

An inline function is created from a string containing the function
body using the `inline' function. The following code defines the
function f(x) = x^2 + 2.

     f = inline("x^2 + 2");

After this it is possible to evaluate f at any x by writing `f(x)'.

 -- Built-in Function:  inline (STR)
 -- Built-in Function:  inline (STR, ARG1, ...)
 -- Built-in Function:  inline (STR, N)
     Create an inline function from the character string STR.  If
     called with a single argument, the arguments of the generated
     function are extracted from the function itself. The generated
     function arguments will then be in alphabetical order. It should
     be noted that i, and j are ignored as arguments due to the
     ambiguity between their use as a variable or their use as an
     inbuilt constant. All arguments followed by a parenthesis are
     considered to be functions.

     If the second and subsequent arguments are character strings, they
     are the names of the arguments of the function.

     If the second argument is an integer N, the arguments are `"x"',
     `"P1"', ..., `"PN"'.

     *See also:* argnames, formula, vectorize.

 -- Built-in Function:  argnames (FUN)
     Return a cell array of character strings containing the names of
     the arguments of the inline function FUN.

     *See also:* inline, formula, vectorize.

 -- Built-in Function:  formula (FUN)
     Return a character string representing the inline function FUN.
     Note that `char (FUN)' is equivalent to `formula (FUN)'.

     *See also:* argnames, inline, vectorize.

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

