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

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

END-INFO-DIR-ENTRY

   Copyright (C) 1996, 1997, 1999, 2000, 2001, 2002, 2005, 2006, 2007,
2011 John W. Eaton.

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

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

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


File: octave.info,  Node: 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.6.2.

* Menu:

* Preface::
* Introduction::                A brief introduction to Octave.
* Getting Started::
* Data Types::
* Numeric Data Types::
* Strings::
* Data Containers::
* Variables::
* Expressions::
* Evaluation::
* Statements::                  Looping and program flow control.
* Functions and Scripts::
* Errors and Warnings::
* Debugging::
* Input and Output::
* Plotting::
* Matrix Manipulation::
* Arithmetic::
* Linear Algebra::
* Vectorization and Faster Code Execution::
* Nonlinear Equations::
* Diagonal and Permutation Matrices::
* Sparse Matrices::
* Numerical Integration::
* Differential Equations::
* Optimization::
* Statistics::
* Sets::
* Polynomial Manipulations::
* Interpolation::
* Geometry::
* Signal Processing::
* Image Processing::
* Audio Processing::
* Object Oriented Programming::
* GUI Development::
* System Utilities::
* Packages::
* Dynamically Linked Functions::
* Test and Demo Functions::
* Tips and Standards::
* Contributing Guidelines::
* Obsolete Functions::
* Trouble::                     If you have trouble installing Octave.
* Installation::                How to configure, compile and install Octave.
* Emacs Octave Support::
* Grammar and Parser::
* Copying::                     The GNU General Public License.
* Concept Index::               An item for each concept.
* 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::

Introduction

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

Comments

* Single Line Comments::
* Block Comments::
* Comments and the Help System::

Data Types

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

Built-in Data Types

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

Numeric Data Types

* Matrices::
* Ranges::
* Single Precision Data Types::
* Integer Data Types::
* Bit Manipulations::
* Logical Values::
* Promotion and Demotion of Data Types::
* Predicates for Numeric Objects::

Matrices

* Empty Matrices::

Integer Data Types

* Integer Arithmetic::

Strings

* Escape Sequences in String Constants::
* Character Arrays::
* Creating Strings::
* Comparing Strings::
* Manipulating Strings::
* String Conversions::
* Character Class Functions::

Creating Strings

* Concatenating Strings::
* Conversion of Numerical Data to Strings::

Data Containers

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

Structures

* Basic Usage and Examples::
* Structure Arrays::
* Creating Structures::
* Manipulating Structures::
* Processing Data in Structures::

Cell Arrays

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

Comma Separated Lists

* Comma Separated Lists Generated from Cell Arrays::
* Comma Separated Lists Generated from Structure Arrays::

Variables

* Global Variables::
* Persistent Variables::
* Status of Variables::

Expressions

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

Index Expressions

* Advanced Indexing::

Calling Functions

* Call by Value::
* Recursion::

Boolean Expressions

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

Evaluation

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

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 `switch' Statement

* Notes for the C Programmer::

The `for' Statement

* Looping Over Structure Elements::

Functions and Scripts

* Defining Functions::
* Multiple Return Values::
* Variable-length Argument Lists::
* Ignoring Arguments::
* Variable-length Return Lists::
* Returning from a Function::
* Default Arguments::
* Function Files::
* Script Files::
* Function Handles Inline Functions and Anonymous Functions::
* Commands::
* Organization of Functions::

Function Files

* Manipulating the Load Path::
* Subfunctions::
* Private Functions::
* Overloading and Autoloading::
* Function Locking::
* Function Precedence::

Function Handles Inline Functions and Anonymous Functions

* Function Handles::
* Anonymous Functions::
* Inline Functions::

Errors and Warnings

* Handling Errors::
* Handling Warnings::

Handling Errors

* Raising Errors::
* Catching Errors::
* Recovering From Errors::

Handling Warnings

* Issuing Warnings::
* Enabling and Disabling Warnings::

Debugging

* Entering Debug Mode::
* Leaving Debug Mode::
* Breakpoints::
* Debug Mode::
* Call Stack::
* Profiling::
* Profiler Example::

Input and Output

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

Basic Input and Output

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

Terminal Output

* Paging Screen Output::

Simple File I/O

* Saving Data on Unexpected Exits::

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

* Introduction to Plotting::
* High-Level Plotting::
* Graphics Data Structures::
* Advanced Plotting::

High-Level Plotting

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

Two-Dimensional Plots

* Axis Configuration::
* Two-dimensional Function Plotting::
* Two-dimensional Geometric Shapes::

Three-Dimensional Plots

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

Graphics Data Structures

* Introduction to Graphics Structures::
* Graphics Objects::
* Graphics Object Properties::
* Searching Properties::
* Managing Default Properties::

Graphics Object Properties

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

Advanced Plotting

* Colors::
* Line Styles::
* Marker Styles::
* Callbacks::
* Application-defined Data::
* Object Groups::
* Graphics Toolkits::

Object Groups

* Data Sources in Object Groups::
* Area Series::
* Bar Series::
* Contour Groups::
* Error Bar Series::
* Line Series::
* Quiver Group::
* Scatter Group::
* Stair Group::
* Stem Series::
* Surface Group::

Graphics Toolkits

* Customizing Toolkit Behavior::

Matrix Manipulation

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

Arithmetic

* Exponents and Logarithms::
* Complex Arithmetic::
* Trigonometry::
* Sums and Products::
* Utility Functions::
* Special Functions::
* Rational Approximations::
* Coordinate Transformations::
* Mathematical Constants::

Linear Algebra

* Techniques Used for Linear Algebra::
* Basic Matrix Functions::
* Matrix Factorizations::
* Functions of a Matrix::
* Specialized Solvers::

Vectorization and Faster Code Execution

* Basic Vectorization::        Basic techniques for code optimization
* Broadcasting::               Broadcasting operations
* Function Application::       Applying functions to arrays, cells, and structs
* Accumulation::               Accumulation functions
* Miscellaneous Techniques::   Other techniques for speeding up code
* Examples::

Nonlinear Equations

* Solvers::
* Minimizers::

Diagonal and Permutation Matrices

* Basic Usage::          Creation and Manipulation of Diagonal and Permutation Matrices
* Matrix Algebra::       Linear Algebra with Diagonal and Permutation Matrices
* Function Support::     Functions That Are Aware of These Matrices
* Example Codes::        Some Examples of Usage
* Zeros Treatment::      The Differences in Treatment of Zero Elements

Basic Usage

* Creating Diagonal Matrices::
* Creating Permutation Matrices::
* Explicit and Implicit Conversions::

Matrix Algebra

* Expressions Involving Diagonal Matrices::
* Expressions Involving Permutation Matrices::

Function Support

* Diagonal Matrix Functions::
* Permutation Matrix Functions::

Sparse Matrices

* Basics::                      Creation and Manipulation of Sparse Matrices
* Sparse Linear Algebra::       Linear Algebra on Sparse Matrices
* Iterative Techniques::        Iterative Techniques
* Real Life Example::           Using Sparse Matrices

Basics

* Storage of Sparse Matrices::
* Creating Sparse Matrices::
* Information::
* Operators and Functions::

Operators and Functions

* Sparse Functions::
* Return Types of Operators and Functions::
* Mathematical Considerations::

Numerical Integration

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

Differential Equations

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

Optimization

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

Statistics

* Descriptive Statistics::
* Basic Statistical Functions::
* Statistical Plots::
* Correlation and Regression Analysis::
* Distributions::
* Tests::
* Random Number Generation::

Sets

* Set Operations::

Polynomial Manipulations

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

Interpolation

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

Geometry

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

Delaunay Triangulation

* Plotting the Triangulation::
* Identifying Points in Triangulation::

Image Processing

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

Object Oriented Programming

* Creating a Class::
* Manipulating Classes::
* Indexing Objects::
* Overloading Objects::
* Inheritance and Aggregation::

Indexing Objects

* Defining Indexing And Indexed Assignment::
* Indexed Assignment Optimization::

Overloading Objects

* Function Overloading::
* Operator Overloading::
* Precedence of Objects::

GUI Development

* I/O Dialogs::
* Progress Bar::
* GUI Utility Functions::
* User-Defined Preferences::

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

Networking Utilities

* FTP Objects::
* URL Manipulation::

Packages

* Installing and Removing Packages::
* Using Packages::
* Administrating Packages::
* Creating Packages::

Creating Packages

* The DESCRIPTION File::
* The INDEX File::
* PKG_ADD and PKG_DEL Directives::

Dynamically Linked Functions

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

Oct-Files

* Getting Started with Oct-Files::
* Matrices and Arrays in Oct-Files::
* Character Strings in Oct-Files::
* Cell Arrays in Oct-Files::
* Structures in Oct-Files::
* Sparse Matrices in Oct-Files::
* Accessing Global Variables in Oct-Files::
* Calling Octave Functions from Oct-Files::
* Calling External Code from Oct-Files::
* Allocating Local Memory in Oct-Files::
* Input Parameter Checking in Oct-Files::
* Exception and Error Handling in Oct-Files::
* Documentation and Test of Oct-Files::

Sparse Matrices in Oct-Files

* Array and Sparse Differences::
* Creating Sparse Matrices in Oct-Files::
* Using Sparse Matrices in Oct-Files::

Mex-Files

* Getting Started with Mex-Files::
* Working with Matrices and Arrays in Mex-Files::
* Character Strings in Mex-Files::
* Cell Arrays with Mex-Files::
* Structures with Mex-Files::
* Sparse Matrices with Mex-Files::
* Calling Other Functions in Mex-Files::

Test and Demo Functions

* Test Functions::
* Demonstration Functions::

Tips and Standards

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

Contributing Guidelines

* How to Contribute::
* Building the Development Sources::
* Basics of Generating a Changeset::
* General Guidelines::
* Octave Sources (m-files)::
* C++ Sources::
* Other Sources::

Trouble

* Actual Bugs::                 Bugs we will fix later.
* Reporting Bugs::
* Service::

Reporting Bugs

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

Installation

* Build Dependencies::
* Running Configure and Make::
* Compiling Octave with 64-bit Indexing::
* Installation Problems::

Build Dependencies

* Obtaining the Depencies Automatically::
* Build Tools::
* External Packages::

Emacs Octave Support

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

Grammar and Parser

* Keywords::
* Parser::


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.  We find that most students pick up the basics of Octave
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.
More recently, Octave has been used as the primary computational tool
for teaching Stanford's online Machine Learning class (`ml-class.org')
taught by Andrew Ng.  Tens of thousands of students participated in the
course.

   If you find Octave useful, please let us know.  We are always
interested to find out how Octave is being used.

   Virtually everyone thinks that the name Octave has something to do
with music, but it is actually the name of one of John W. Eaton's former
professors 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::).  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 contributed to Octave's development.  The following
people have helped code parts of Octave or aided in various other ways
(listed alphabetically).

Ben Abbott               Andy Adler               Giles Anderson
Joel Andersson           Muthiah Annamalai        Marco Atzeri
Shai Ayal                Roger Banks              Ben Barrowes
Alexander Barth          David Bateman            Heinz Bauschke
Roman Belov              Karl Berry               David Billinghurst
Don Bindner              Jakub Bogusz             Moritz Borgmann
Paul Boven               Richard Bovey            John Bradshaw
Marcus Brinkmann         Remy Bruno               Ansgar Burchard
Marco Caliari            Daniel Calvelo           John C. Campbell
Juan Pablo Carbajal      Jean-Francois Cardoso    Joao Cardoso
Larrie Carr              David Castelow           Vincent Cautaerts
Clinton Chee             Albert Chin-A-Young      Carsten Clark
J. D. Cole               Martin Costabel          Michael Creel
Jeff Cunningham          Martin Dalecki           Jorge Barros de Abreu
Carlo de Falco           Jacob Dawid              Thomas D. Dean
Philippe Defert          Bill Denney              Fabian Deutsch
Christos Dimitrakakis    David M. Doolin          Carnë Draug
Pascal A. Dupuis         John W. Eaton            Dirk Eddelbuettel
Pieter Eendebak          Paul Eggert              Stephen Eglen
Peter Ekberg             Rolf Fabian              Gunnar Farnebäck
Stephen Fegan            Ramon Garcia Fernandez   Torsten Finke
Jose Daniel Munoz Frias  Brad Froehle             Castor Fu
Eduardo Gallestey        Walter Gautschi          Klaus Gebhardt
Driss Ghaddab            Nicolo Giorgetti         Michael D. Godfrey
Michael Goffioul         Glenn Golden             Tomislav Goles
Keith Goodman            Brian Gough              Steffen Groot
Etienne Grossmann        David Grundberg          Peter Gustafson
Kai Habel                Patrick Häcker           William P. Y.
                                                  Hadisoeseno
Jaroslav Hajek           Benjamin Hall            Kim Hansen
Søren Hauberg            Dave Hawthorne           Daniel Heiserer
Martin Helm              Stefan Hepp              Jordi Gutiérrez Hermoso
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             Matthias Jüschke
Atsushi Kajita           Jarkko Kaleva            Mohamed Kamoun
Lute Kamstra             Fotios Kasolis           Thomas Kasper
Joel Keay                Mumit Khan               Paul Kienzle
Aaron A. King            Arno J. Klaassen         Alexander Klein
Geoffrey Knauth          Heine Kolltveit          Ken Kouno
Kacper Kowalik           Daniel Kraft             Aravindh Krishnamoorthy
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         Jyh-miin Lin             Timo Lindfors
Benjamin Lindner         Ross Lippert             David Livings
Sebastien Loisel         Erik de Castro Lopo      Massimo Lorenzin
Emil Lucretiu            Hoxide Ma                James Macnicol
Jens-Uwe Mager           Rob Mahurin              Ricardo Marranita
Orestes Mas              Makoto Matsumoto         Tatsuro Matsuoka
Laurent Mazet            G. D. McBain             Alexander Mamonov
Christoph Mayer          Júlio Hoffimann Mendes   Thorsten Meyer
Petr Mikulik             Stefan Monnier           Antoine Moreau
Kai P. Mueller           Hannes Müller            Victor Munoz
Carmen Navarrete         Todd Neal                Philip Nienhuis
Al Niessner              Rick Niles               Takuji Nishimura
Kai Noda                 Eric Norum               Krzesimir Nowak
Michael O'Brien          Peter O'Gorman           Thorsten Ohl
Arno Onken               Luis F. Ortiz            Scott Pakin
Gabriele Pannocchia      Sylvain Pelissier        Per Persson
Primozz Peterlin         Jim Peterson             Danilo Piazzalunga
Nicholas Piper           Elias Pipping            Robert Platt
Hans Ekkehard Plesser    Tom Poage                Orion Poplawski
Ondrej Popp              Jef Poskanzer            Francesco Potortì
Konstantinos Poulios     Jarno Rajahalme          James B. Rawlings
Eric S. Raymond          Balint Reczey            Joshua Redstone
Lukas Reichlin           Michael Reifenberger     Anthony Richardson
Jason Riedy              E. Joshua Rigler         Petter Risholm
Matthew W. Roberts       Andrew Ross              Mark van Rossum
Joe Rothweiler           Kevin Ruland             Kristian Rumberg
Ryan Rusaw               Olli Saarela             Toni Saarela
Juhani Saastamoinen      Radek Salac              Ben Sapp
Aleksej Saushev          Alois Schlögl            Michel D. Schmid
Julian Schnidder         Nicol N. Schraudolph     Sebastian Schubert
Ludwig Schwardt          Thomas L. Scofield       Daniel J. Sebald
Dmitri A. Sergatskov     Vanya Sergeev            Baylis Shanks
Andriy Shinkarchuck      Robert T. Short          Joseph P. Skudlarek
John Smith               Julius Smith             Shan G. Smith
Peter L. Sondergaard     Joerg Specht             Quentin H. Spencer
Christoph Spiel          Richard Stallman         Russell Standish
Brett Stewart            Doug Stewart             Jonathan Stickel
Judd Storrs              Thomas Stuart            Ivan Sutoris
John Swensen             Daisuke Takago           Ariel Tankus
Matthew Tenny            Georg Thimm              Duncan Temple Lang
Kris Thielemans          Olaf Till                Christophe Tournery
Thomas Treichl           Karsten Trulsen          Frederick Umminger
Utkarsh Upadhyay         Stefan van der Walt      Peter Van Wieren
James R. Van Zandt       Gregory Vanuxem          Ivana Varekova
Thomas Walter            Andreas Weber            Olaf Weber
Thomas Weber             Rik Wehbring             Bob Weigel
Andreas Weingessel       Martin Weiser            Michael Weitzel
David Wells              Fook Fah Yap             Sean Young
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 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.  *Note Contributing Guidelines::, for
detailed information on contributing new code.

   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.

   Donations supporting Octave development may be made on the web at
`https://my.fsf.org/donate/working-together/octave'.  These donations
also help to support the Free Software Foundation

   If you'd prefer to pay by check or money order, you can do so by
sending a check to the FSF at the following address:

     Free Software Foundation
     51 Franklin Street, Suite 500
     Boston, MA 02110-1335
     USA

If you pay by check, please be sure to write "GNU Octave" in the memo
field of your check.

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

   To download a copy of Octave, please visit
`http://www.octave.org/download.html'.


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

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

GNU Octave is a high-level language, primarily intended for numerical
computations.  It provides a convenient interactive 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 for data processing.

   GNU Octave is 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 manual provides comprehensive documentation on how to install,
run, use, and extend GNU Octave.  Additional chapters describe how to
report bugs and help contribute code.

   This document corresponds to Octave version 3.6.2.

* Menu:

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


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

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

On most systems, Octave is started 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' (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 like so, `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 Elementary Calculations
-----------------------------

Octave can easily be used for basic numerical calculations.  Octave
knows about arithmetic operations (+,-,*,/), exponentiation (^),
natural logarithms/exponents (log, exp), and the trigonometric
functions (sin, cos, ...).  Moreover, Octave calculations work on real
or imaginary numbers (i,j).  In addition, some mathematical constants
such as the base of the natural logarithm (e) and the ratio of a
circle's circumference to its diameter (pi) are pre-defined.

For example, to verify Euler's Identity,

      i*pi
     e     = -1

type the following which will evaluate to `-1' within the tolerance of
the calculation.

     octave:1> exp(i*pi)

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

Vectors and matrices are the basic building blocks for numerical
analysis.  To create a new matrix and store it in a variable so that
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.
Octave uses a comma or space to separate entries in a row, and a
semicolon or carriage return to separate one row from the next.  Ending
a command with a semicolon tells Octave not to print the result of the
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 a variable, simply type the name of the
variable at the prompt.  For example, to display the value stored in the
matrix `B', type the command

     octave:3> B

1.2.3 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.4 Solving Systems of Linear Equations
-----------------------------------------

Systems of linear equations are ubiquitous in numerical analysis.  To
solve the set of linear equations `AX = b', use the left division
operator, `\':

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

   A simple example comes from chemistry and the need to obtain balanced
chemical equations.  Consider the burning of hydrogen and oxygen to
produce water.

     H2 + O2 --> H2O

The equation above is not accurate.  The Law of Conservation of Mass
requires that the number of molecules of each type balance on the left-
and right-hand sides of the equation.  Writing the variable overall
reaction with individual equations for hydrogen and oxygen one finds:

     x1*H2 + x2*O2 --> H2O
     H: 2*x1 + 0*x2 --> 2
     O: 0*x1 + 2*x2 --> 1

The solution in Octave is found in just three steps.

     octave:1> A = [ 2, 0; 0, 2 ];
     octave:2> b = [ 2; 1 ];
     octave:3> x = A \ b

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

     octave:2> 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)

     octave:3> t = linspace (0, 50, 200)';

it is easy to integrate the set of differential equations:

     octave:4> 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.6 Producing Graphical Output
--------------------------------

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

     octave:1> 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 in Encapsulated PostScript format.  The command

     help print

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

1.2.7 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' (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.8 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 type `help --list'.  This
will show you all the operators, keywords, built-in functions, and
loadable functions available in the current session of Octave.  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 variables or function arguments appear in this font or
form: FIRST-NUMBER.  Commands that you type at the shell prompt 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.
In this manual the printed text resulting from an example is indicated
by `-|'.  The value that is returned by evaluating the expression is
displayed with `=>' (`1' in the next example) 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 beginning with
`error:'.

     fieldnames ([1, 2; 3, 4])
     error: fieldnames: 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 File:  foo (X)
 -- Function File:  foo (X, Y)
 -- Function File:  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
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 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.

`--doc-cache-file FILENAME'
     Specify the name of the doc cache file to use.  The value of
     FILENAME specified on the command line will override any value of
     `OCTAVE_DOC_CACHE_FILE' found in the environment, but not any
     commands in the system or user startup files that use the
     `doc_cache_file' function.

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

`--eval CODE'
     Evaluate CODE and exit when finished 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'
     Add path to the head of the search path for images.  The value of
     PATH specified on the command line will override any value of
     `OCTAVE_IMAGE_PATH' found in the environment, but not any commands
     in the system or user startup files that set the built-in variable
     `IMAGE_PATH'.

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

`--line-editing'
     Force readline use for command-line editing.

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

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

`--no-init-path'
     Don't initialize the search path for function files to include
     default locations.

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

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

`--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'
     Add path to the head of the search path 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                             = ""
          allow_noninteger_range_as_index = true
          beep_on_error                   = true
          confirm_recursive_rmdir         = false
          crash_dumps_octave_core         = false
          default_save_options            = "-mat-binary"
          do_braindead_shortcircuit_evaluation = true
          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:abbreviated-property-match
          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 functions which return 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 the value returned by
     `program_invocation_name'.

     *See also:* *note program_invocation_name:
     doc-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:* *note program_name: doc-program_name.

   Here is an example of using these functions to reproduce the command
line which invoked Octave.

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

*Note Indexing Cell Arrays::, for an explanation of how to retrieve
objects from cell arrays, 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 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.  Care should be taken when making changes to this file
     since all users of Octave at your site will be affected.  The
     default file may be overridden by the environment variable
     `OCTAVE_SITE_INITFILE'.

`OCTAVE-HOME/share/octave/VERSION/m/startup/octaverc'
     where OCTAVE-HOME is the directory in which 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 of a
     particular version of Octave.  Care should be taken when making
     changes to this file since all users of Octave at your site will be
     affected.  The default file may be overridden by the environment
     variable `OCTAVE_VERSION_INITFILE'.

`~/.octaverc'
     This file is 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 where Octave searches for `.octaverc'.

     If you start Octave in your home directory, commands 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.

   The `dump_prefs' function is useful for determining what
customizations to Octave are possible and which are in effect.

 -- Function File:  dump_prefs ()
 -- Function File:  dump_prefs (FID)
     Dump all of the current user preference variables in a format that
     can be parsed by Octave later.  FID is a file descriptor as
     returned by `fopen'.  If FILE is omitted, the listing is printed
     to stdout.


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)
 -- Built-in Function:  atexit (FCN, FLAG)
     Register a function to be called when Octave exits.  For example,

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

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

     The additional argument FLAG will register or unregister FCN from
     the list of functions to be called when Octave exits.  If FLAG is
     true, the function is registered, and if FLAG is false, it is
     unregistered.  For example, after registering the function
     `last_words' above,

          atexit ("last_words", false);

     will remove the function from the list and Octave will not call
     `last_words' 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
 -- Command:  help `--list'
     Display the help text for NAME.   For example, the command `help
     help' prints a short message describing the `help' command.

     Given the single argument `--list', list all operators, keywords,
     built-in functions, and loadable functions available in the
     current session of Octave.

     If invoked without any arguments, `help' display instructions on
     how to access help from the command line.

     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:* *note doc: doc-doc, *note lookfor: doc-lookfor, *note
     which: doc-which.

 -- 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
     the `rand' 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:* *note help: doc-help.

 -- Command:  lookfor STR
 -- Command:  lookfor -all STR
 -- Function File: [FUNC, HELPSTRING] = lookfor (STR)
 -- Function File: [FUNC, HELPSTRING] = lookfor ('-all', STR)
     Search for the string STR in all functions found in the current
     function search path.  By default, `lookfor' searches for STR in
     the first sentence of the help string of each function found.  The
     entire help text of each function 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 FUNC and HELPSTRING define the matching functions and the
     first sentence of each of their help strings.

     The ability of `lookfor' to correctly identify the first sentence
     of the help text is dependent on the format of the function's
     help.  All Octave core functions are correctly formatted, but the
     same can not be guaranteed for external packages and user-supplied
     functions.  Therefore, the use of the '-all' argument may be
     necessary to find related functions that are not a part of Octave.

     *See also:* *note help: doc-help, *note doc: doc-doc, *note which:
     doc-which.

   To see what is new in the current release of Octave, use the `news'
function.

 -- Function File:  news (PACKAGE)
     Display the current NEWS file for Octave or installed package.

     If PACKAGE is the name of an installed package, display the current
     NEWS file for that package.

 -- Function File:  info ()
     Display contact information for the GNU Octave community.

 -- Built-in Function:  warranty ()
     Describe the conditions for copying and distributing Octave.

   The following functions 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)
 -- Built-in Function:  info_file (NEW_VAL, "local")
     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 root
     directory of the Octave installation.  The default value may be
     overridden by the environment variable `OCTAVE_INFO_FILE', or the
     command line argument `--info-file NAME'.

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

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

 -- Built-in Function: VAL = info_program ()
 -- Built-in Function: OLD_VAL = info_program (NEW_VAL)
 -- Built-in Function:  info_program (NEW_VAL, "local")
     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 root directory of the Octave installation,
     VERSION is the Octave version number, and ARCH is the system type
     (for example, `i686-pc-linux-gnu').  The default value may be
     overridden by the environment variable `OCTAVE_INFO_PROGRAM', or
     the command line argument `--info-program NAME'.

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

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

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

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

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

 -- Built-in Function: VAL = doc_cache_file ()
 -- Built-in Function: OLD_VAL = doc_cache_file (NEW_VAL)
 -- Built-in Function:  doc_cache_file (NEW_VAL, "local")
     Query or set the internal variable that specifies the name of the
     Octave documentation cache file.  A cache file significantly
     improves the performance of the `lookfor' command.  The default
     value is `OCTAVE-HOME/share/octave/VERSION/etc/doc-cache', in
     which OCTAVE-HOME is the root directory of the Octave installation,
     and VERSION is the Octave version number.  The default value may
     be overridden by the environment variable `OCTAVE_DOC_CACHE_FILE',
     or the command line argument `--doc-cache-file NAME'.

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

     *See also:* *note lookfor: doc-lookfor, *note info_program:
     doc-info_program, *note doc: doc-doc, *note help: doc-help, *note
     makeinfo_program: doc-makeinfo_program.

 -- Built-in Function: VAL = suppress_verbose_help_message ()
 -- Built-in Function: OLD_VAL = suppress_verbose_help_message (NEW_VAL)
 -- Built-in Function:  suppress_verbose_help_message (NEW_VAL, "local")
     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.

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

   The following functions are principally used internally by Octave for
generating the documentation.  They are documented here for completeness
and because they may occasionally be useful for users.

 -- Function File:  gen_doc_cache (OUT_FILE, DIRECTORY)
     Generate documentation caches for all functions in a given
     directory.

     A documentation cache is generated for all functions in DIRECTORY.
     The resulting cache is saved in the file OUT_FILE.  The cache is
     used to speed up `lookfor'.

     If no directory is given (or it is the empty matrix), a cache for
     builtin operators, etc. is generated.

     *See also:* *note lookfor: doc-lookfor, *note path: doc-path.

 -- Loadable Function: [TEXT, FORMAT] = get_help_text (NAME)
     Return the raw help text of function NAME.

     The raw help text is returned in TEXT and the format in FORMAT The
     format is a string which is one of "texinfo", "html", or "plain
     text".

 -- Loadable Function: [TEXT, FORMAT] = get_help_text_from_file (FNAME)
     Return the raw help text from the file FNAME.

     The raw help text is returned in TEXT and the format in FORMAT The
     format is a string which is one of "texinfo", "html", or "plain
     text".

 -- Function File: [TEXT, STATUS] = get_first_help_sentence (NAME)
 -- Function File: [TEXT, STATUS] = get_first_help_sentence (NAME,
          MAX_LEN)
     Return the first sentence of a function's help text.

     The first sentence is defined as the text after the function
     declaration until either the first period (".") or the first
     appearance of two consecutive newlines ("\n\n").  The text is
     truncated to a maximum length of MAX_LEN, which defaults to 80.

     The optional output argument STATUS returns the status reported by
     `makeinfo'.  If only one output argument is requested, and STATUS
     is non-zero, a warning is displayed.

     As an example, the first sentence of this help text is

          get_first_help_sentence ("get_first_help_sentence")
          -| ans = Return the first sentence of a function's help text.


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.  In addition, all of the editing
functions can be bound to different key strokes at the user's
discretion.  This manual assumes no changes from the default Emacs
bindings.  See the GNU Readline Library manual for more information on
customizing Readline and for a complete feature list.

   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.
To type `M-u', hold down the <META> key and press <u>.  Depending on
the keyboard, the <META> key may be labeled <ALT> or even <WINDOWS>.
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 would 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.

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

`<DEL>'
     Delete the character underneath 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 action.  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 left and right 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)
 -- Built-in Function:  completion_append_char (NEW_VAL, "local")
     Query or set the internal character variable that is appended to
     successful command-line completion attempts.  The default value is
     `" "' (a single space).

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

 -- 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 current line regardless of where the cursor is.  If the
     line is non-empty, add it to the history list.  If the 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 up and down 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, appending its contents to the current
          history list.  If the name is omitted, use the default
          history file (normally `~/.octave_hist').

    `N'
          Display only the most recent N lines of history.

    `-q'
          Don't number the displayed lines of history.  This is useful
          for cutting and pasting commands 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 [FIRST] [LAST]
     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.

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

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

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

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

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

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

     *See also:* *note history_control: doc-history_control, *note
     history_file: doc-history_file, *note history_size:
     doc-history_size, *note history_timestamp_format_string:
     doc-history_timestamp_format_string.

 -- Built-in Function: VAL = history_control ()
 -- Built-in Function: OLD_VAL = history_control (NEW_VAL)
     Query or set the internal variable that specifies how commands are
     saved to the history list.  The default value is an empty
     character string, but may be overridden by the environment variable
     `OCTAVE_HISTCONTROL'.

     The value of `history_control' is a colon-separated list of values
     controlling how commands are saved on the history list.  If the
     list of values includes `ignorespace', lines which begin with a
     space character are not saved in the history list.  A value of
     `ignoredups' causes lines matching the previous history entry to
     not be saved.  A value of `ignoreboth' is shorthand for
     `ignorespace' and `ignoredups'.  A value of `erasedups' causes all
     previous lines matching the current line to be removed from the
     history list before that line is saved.  Any value not in the
     above list is ignored.  If `history_control' is the empty string,
     all commands are saved on the history list, subject to the value
     of `saving_history'.

     *See also:* *note history_file: doc-history_file, *note
     history_size: doc-history_size, *note
     history_timestamp_format_string:
     doc-history_timestamp_format_string, *note saving_history:
     doc-saving_history.

 -- 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:* *note history_size: doc-history_size, *note
     saving_history: doc-saving_history, *note
     history_timestamp_format_string:
     doc-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:* *note history_file: doc-history_file, *note
     history_timestamp_format_string:
     doc-history_timestamp_format_string, *note saving_history:
     doc-saving_history.

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

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

     *See also:* *note strftime: doc-strftime, *note history_file:
     doc-history_file, *note history_size: doc-history_size, *note
     saving_history: doc-saving_history.

 -- Built-in Function: VAL = EDITOR ()
 -- Built-in Function: OLD_VAL = EDITOR (NEW_VAL)
 -- Built-in Function:  EDITOR (NEW_VAL, "local")
     Query or set the internal variable that specifies the editor to
     use with the `edit_history' command.  The default value is taken
     from the environment variable `EDITOR' when Octave starts.  If the
     environment variable is not initialized, `EDITOR' will be set to
     `"emacs"'.

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

     *See also:* *note edit_history: doc-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'
----------------------------

Octave uses the GNU Readline library for command-line editing and
history features.  Readline is very flexible and can be modified through
a configuration file of commands (See the GNU Readline library for the
exact command syntax).  The default configuration file is normally
`~/.inputrc'.

   Octave provides two commands for initializing Readline and thereby
changing the command line behavior.

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

 -- Built-in Function:  re_read_readline_init_file ()
     Re-read the last readline library initialization file that was
     read.  *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)
 -- Built-in Function:  PS1 (NEW_VAL, "local")
     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

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

     You can also use ANSI escape sequences if your terminal supports
     them.  This can be useful for coloring the prompt.  For example,

          PS1 ("\\[\\033[01;31m\\]\\s:\\#> \\[\\033[0m\]")

     will give the default Octave prompt a red coloring.

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

     *See also:* *note PS2: doc-PS2, *note PS4: doc-PS4.

 -- Built-in Function: VAL = PS2 ()
 -- Built-in Function: OLD_VAL = PS2 (NEW_VAL)
 -- Built-in Function:  PS2 (NEW_VAL, "local")
     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 `"> "'.

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

     *See also:* *note PS1: doc-PS1, *note PS4: doc-PS4.

 -- Built-in Function: VAL = PS4 ()
 -- Built-in Function: OLD_VAL = PS4 (NEW_VAL)
 -- Built-in Function:  PS4 (NEW_VAL, "local")
     Query or set the character string used to prefix output produced
     when echoing commands is enabled.  The default value is `"+ "'.
     *Note Diary and Echo Commands::, for a description of echoing
     commands.

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

     *See also:* *note echo: doc-echo, *note echo_executing_commands:
     doc-echo_executing_commands, *note PS1: doc-PS1, *note PS2:
     doc-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
     Record 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.

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

     With no arguments, `echo' toggles the current echo state.

 -- Built-in Function: VAL = echo_executing_commands ()
 -- Built-in Function: OLD_VAL = echo_executing_commands (NEW_VAL)
 -- Built-in Function:  echo_executing_commands (NEW_VAL, "local")
     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' may be set by the `echo'
     command or the command line option `--echo-commands'.

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.


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> function y = f (x) y = x***2; endfunction

Octave will respond immediately with a message like this:

     parse error:

       syntax error

     >>> function 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 for
exponentiation (`**') was misspelled.  It marked the error at the third
`*' because the code leading up to this was correct but the final `*'
was not understood.

   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: called from:
     error:   f at line 1, column 22

This error message has several parts, and gives 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 outside of an enclosing function, the
line number indicates the input line number, which is usually displayed
in the primary prompt string.

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

     error:   g at line 1, column 17

   These lists of function calls 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.  Octave scripts are also used for batch
processing of data files.  Once an algorithm has been developed and
tested in the interactive portion of Octave, it can be committed to an
executable script and used again and again on new data files.

   As a trivial example of an executable Octave script, you might
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 path
and name of your Octave binary).  Note that this will only work if `#!'
appears at the very beginning of the file.  After making the file
executable (with the `chmod' command on Unix systems), 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 path and filename 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 executable.  The rest of the argument list will either be
options to Octave, or data files, or both.  The `-qf' options are
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 arguments
appearing in a `#!' line are parsed differently by various
shells/systems.  The majority of them group all the arguments together
in one 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 typing at the command line:

     octave "-q -f # comment"

which will produce an error message.  Unfortunately, it is not possible
for Octave to determine 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 the 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 was
used to execute the 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 which is NOT an executable 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.

* Menu:

* Single Line Comments::
* Block Comments::
* Comments and the Help System::


File: octave.info,  Node: Single Line Comments,  Next: Block Comments,  Up: Comments

2.7.1 Single Line Comments
--------------------------

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.  Any text following the sharp sign or percent symbol is
ignored by the Octave interpreter and not executed.  The following
example shows whole line and partial line comments.

     function countdown
       # Count down for main rocket engines
       disp(3);
       disp(2);
       disp(1);
       disp("Blast Off!");  # Rocket leaves pad
     endfunction


File: octave.info,  Node: Block Comments,  Next: Comments and the Help System,  Prev: Single Line Comments,  Up: Comments

2.7.2 Block Comments
--------------------

Entire blocks of code can be commented by enclosing the code between
matching `#{' and `#}' or `%{' and `%}' markers.  For example,

     function quick_countdown
       # Count down for main rocket engines
       disp(3);
      #{
       disp(2);
       disp(1);
      #}
       disp("Blast Off!");  # Rocket leaves pad
     endfunction

will produce a very quick countdown from '3' to 'Blast Off' as the
lines "`disp(2);'" and "`disp(1);'" won't be executed.

   The block comment markers must appear alone as the only characters
on a line (excepting whitespace) in order to be parsed correctly.


File: octave.info,  Node: Comments and the Help System,  Prev: Block Comments,  Up: Comments

2.7.3 Comments and the Help System
----------------------------------

The `help' command (*note Getting Help::) is able to find the first
block of comments in a function and return those as a documentation
string.  This means that the same commands used to get help on built-in
functions are available for properly formatted user-defined functions.
For example, after defining the function `f' below,

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

   The `help' parser currently only recognizes single line comments
(*note Single Line Comments::) and not block comments for the initial
help text.


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 ()
 -- Built-in Function:  typeinfo (EXPR)
     Return the type of the expression EXPR, as a string.  If EXPR is
     omitted, return an cell 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)
 -- Built-in Function:  class (S, ID)
 -- Built-in Function:  class (S, ID, P, ...)
     Return the class of the expression EXPR or create a class with
     fields from structure S and name (string) ID.  Additional
     arguments name a list of parent classes from which the new class is
     derived.

 -- Function File:  isa (OBJ, CLASS)
     Return true if OBJ is an object from the class CLASS.

     *See also:* *note class: doc-class, *note typeinfo: doc-typeinfo.

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

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

 -- Loadable Function:  typecast (X, CLASS)
     Return a new array Y resulting from interpreting the data of X in
     memory as data of the numeric class CLASS.  Both the class of X
     and CLASS must be one of the built-in numeric classes:

            "logical"
            "char"
            "int8"
            "int16"
            "int32"
            "int64"
            "uint8"
            "uint16"
            "uint32"
            "uint64"
            "double"
            "single"
            "double complex"
            "single complex"

     the last two are reserved for CLASS; they indicate that a
     complex-valued result is requested.  Complex arrays are stored in
     memory as consecutive pairs of real numbers.  The sizes of integer
     types are given by their bit counts.  Both logical and char are
     typically one byte wide; however, this is not guaranteed by C++.
     If your system is IEEE conformant, single and double should be 4
     bytes and 8 bytes wide, respectively.  "logical" is not allowed
     for CLASS.  If the input is a row vector, the return value is a
     row vector, otherwise it is a column vector.  If the bit length of
     X is not divisible by that of CLASS, an error occurs.

     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:* *note cast: doc-cast, *note bitunpack: doc-bitunpack,
     *note bitpack: doc-bitpack, *note swapbytes: doc-swapbytes.

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

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

     *See also:* *note typecast: doc-typecast, *note cast: doc-cast.

 -- Loadable Function: Y = bitpack (X, CLASS)
     Return a new array Y resulting from interpreting an array X as raw
     bit patterns for data of the numeric class CLASS.  CLASS must be
     one of the built-in numeric classes:

            "char"
            "int8"
            "int16"
            "int32"
            "int64"
            "uint8"
            "uint16"
            "uint32"
            "uint64"
            "double"
            "single"

     The number of elements of X should be divisible by the bit length
     of CLASS.  If it is not, excess bits are discarded.  Bits come in
     increasing order of significance, i.e., `x(1)' is bit 0, `x(2)' is
     bit 1, etc.  The result is a row vector if X is a row vector,
     otherwise it is a column vector.

     *See also:* *note bitunpack: doc-bitunpack, *note typecast:
     doc-typecast.

 -- Loadable Function: Y = bitunpack (X)
     Return an array Y corresponding to the raw bit patterns of X.  X
     must belong to one of the built-in numeric classes:

            "char"
            "int8"
            "int16"
            "int32"
            "int64"
            "uint8"
            "uint16"
            "uint32"
            "uint64"
            "double"
            "single"

     The result is a row vector if X is a row vector; otherwise, it is a
     column vector.

     *See also:* *note bitpack: doc-bitpack, *note typecast:
     doc-typecast.

* 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
 -- Built-in Function:  NA (N)
 -- Built-in Function:  NA (N, M)
 -- Built-in Function:  NA (N, M, K, ...)
 -- Built-in Function:  NA (..., CLASS)
     Return a scalar, matrix, or N-dimensional array whose elements are
     all equal to the special constant used to designate missing values.

     Note that NA always compares not equal to NA (NA != NA).  To find
     NA values, use the `isna' function.

     When called with no arguments, return a scalar with the value `NA'.
     When called with a single argument, return a square matrix with
     the dimension specified.  When called with more than one scalar
     argument the first two arguments are taken as the number of rows
     and columns and any further arguments specify additional matrix
     dimensions.  The optional argument CLASS specifies the return type
     and may be either "double" or "single".

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

 -- Mapping Function:  isna (X)
     Return a logical array which is true where the elements of X are
     NA (missing) values and false where they are not.  For example:

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

     *See also:* *note isnan: doc-isnan, *note isinf: doc-isinf, *note
     isfinite: doc-isfinite.


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 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)
     Return the number of dimensions of A.  For any array, the result
     will always be larger than or equal to 2.  Trailing singleton
     dimensions are not counted.

            ndims (ones (4, 1, 2, 1))
               => 3

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

     *See also:* *note rows: doc-rows, *note size: doc-size, *note
     length: doc-length, *note numel: doc-numel, *note isscalar:
     doc-isscalar, *note isvector: doc-isvector, *note ismatrix:
     doc-ismatrix.

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

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

 -- Built-in Function:  numel (A)
 -- Built-in Function:  numel (A, IDX1, IDX2, ...)
     Return the number of elements in the object A.  Optionally, if
     indices IDX1, IDX2, ... are supplied, return the number of
     elements that would result from the indexing

            A(IDX1, IDX2, ...)

     Note that the indices do not have to be numerical.  For example,

            A = 1;
            B = ones (2, 3);
            numel (A, B);

     will return 6, as this is the number of ways to index with B.

     This method is also called when an object appears as lvalue with
     cs-list indexing, i.e., `object{...}' or `object(...).field'.

     *See also:* *note size: doc-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)
 -- Built-in Function:  size (A, DIM)
     Return the number of 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:* *note numel: doc-numel.

 -- Built-in Function:  isempty (A)
     Return true if A is an empty matrix (any one of its dimensions is
     zero).  Otherwise, return false.

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

 -- Built-in Function:  isnull (X)
     Return true if X is a special null matrix, string, or single quoted
     string.  Indexed assignment with such a value on the right-hand
     side should delete array elements.  This function should be used
     when overloading indexed assignment for user-defined classes
     instead of `isempty', to distinguish the cases:
    `A(I) = []'
          This should delete elements if `I' is nonempty.

    `X = []; A(I) = X'
          This should give an error if `I' is nonempty.

     *See also:* *note isempty: doc-isempty, *note isindex: doc-isindex.

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

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

 -- Built-in Function:  size_equal (A, B, ...)
     Return true if the dimensions of all arguments agree.  Trailing
     singleton dimensions are ignored.  Called with a single or no
     argument, size_equal returns true.

     *See also:* *note size: doc-size, *note numel: doc-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:

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

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

 -- Built-in Function:  complex (X)
 -- Built-in Function:  complex (RE, IM)
     Return a complex result from real arguments.  With 1 real argument
     X, return the complex result `X + 0i'.  With 2 real arguments,
     return the complex result `RE + IM'.  `complex' can often be more
     convenient than expressions such as `a + i*b'.  For example:

          complex ([1, 2], [3, 4])
          =>
             1 + 3i   2 + 4i

     *See also:* *note real: doc-real, *note imag: doc-imag, *note
     iscomplex: doc-iscomplex.

* Menu:

* Matrices::
* Ranges::
* Single Precision Data Types::
* Integer Data Types::
* Bit Manipulations::
* Logical Values::
* Promotion and Demotion of Data Types::
* 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 (1 != 2) 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

     parse error:

       syntax error

     >>> [ 1 a ' ]
                   ^

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.

   The maximum number of elements in a matrix is fixed when Octave is
compiled.  The allowable number can be queried with the function
`sizemax'.  Note that other factors, such as the amount of memory
available on your machine, may limit the maximum size of matrices to
something smaller.

 -- Built-in Function:  sizemax ()
     Return the largest value allowed for the size of an array.  If
     Octave is compiled with 64-bit indexing, the result is of class
     int64, otherwise it is of class int32.  The maximum array size is
     slightly smaller than the maximum value allowable for the relevant
     class as reported by `intmax'.

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

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

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

     *See also:* *note format: doc-format, *note fixed_point_format:
     doc-fixed_point_format, *note output_precision:
     doc-output_precision.

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

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

     *See also:* *note format: doc-format, *note fixed_point_format:
     doc-fixed_point_format, *note output_max_field_width:
     doc-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)
 -- Built-in Function:  split_long_rows (NEW_VAL, "local")
     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

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

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

   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)
 -- Built-in Function:  fixed_point_format (NEW_VAL, "local")
     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.

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

     *See also:* *note format: doc-format, *note
     output_max_field_width: doc-output_max_field_width, *note
     output_precision: doc-output_precision.

* 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)
 -- Built-in Function:  print_empty_dimensions (NEW_VAL, "local")
     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)

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

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

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

   A common example of when it does become necessary to convert ranges
into vectors occurs when they appear within a vector (i.e., inside
square brackets).  For instance, whereas

     x = 0 : 0.1 : 1;

defines X to be a variable of type `range' and occupies 24 bytes of
memory, the expression

     y = [ 0 : 0.1 : 1];

defines Y to be of type `matrix' and occupies 88 bytes of memory.

   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 adding a scalar to a range, subtracting a scalar from it (or
subtracting a range from a scalar) and multiplying by scalar, Octave
will attempt to avoid unpacking the range and keep the result as a
range, too, if it can determine that it is safe to do so.  For
instance, doing

     a = 2*(1:1e7) - 1;

will produce the same result as `1:2:2e7-1', but without ever forming a
vector with ten million elements.

   Using zero as an increment in the colon notation, as `1:0:1' is not
allowed, because a division by zero would occur in determining the
number of range elements.  However, ranges with zero increment (i.e.,
all elements equal) are useful, especially in indexing, and Octave
allows them to be constructed using the built-in function "ones".  Note
that because a range must be a row vector, `ones (1, 10)' produces a
range, while `ones (10, 1)' does not.

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

4.3 Single Precision Data Types
===============================

Octave includes support for single precision data types, and most of the
functions in Octave accept single precision values and return single
precision answers.  A single precision variable is created with the
`single' function.

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

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

   for example:

     sngl = single (rand (2, 2))
          => sngl =
             0.37569   0.92982
             0.11962   0.50876
     class (sngl)
         => single

   Many functions can also return single precision values directly.  For
example

     ones (2, 2, "single")
     zeros (2, 2, "single")
     eye (2, 2,  "single")
     rand (2, 2, "single")
     NaN (2, 2, "single")
     NA (2, 2, "single")
     Inf (2, 2, "single")

will all return single precision matrices.


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

4.4 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
     Octave are double precision floating point values.

     *See also:* *note isfloat: doc-isfloat, *note ischar: doc-ischar,
     *note islogical: doc-islogical, *note isnumeric: doc-isnumeric,
     *note isa: doc-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:* *note intmin: doc-intmin, *note bitmax: doc-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:* *note intmax: doc-intmax, *note bitmax: doc-bitmax.

* Menu:

* Integer Arithmetic::


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

4.4.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 `./' work 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.

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

 -- Function File:  idivide (X, Y, OP)
     Integer division with different rounding rules.

     The standard behavior of integer division such as `A ./ B' is to
     round the result to the nearest integer.  This is not always the
     desired behavior and `idivide' permits integer element-by-element
     division to be performed with different treatment for the
     fractional part of the division as determined by the OP flag.  OP
     is a string with one of the values:

    "fix"
          Calculate `A ./ B' with the fractional part rounded towards
          zero.

    "round"
          Calculate `A ./ B' with the fractional part rounded towards
          the nearest integer.

    "floor"
          Calculate `A ./ B' with the fractional part rounded towards
          negative infinity.

    "ceil"
          Calculate `A ./ B' with the fractional part rounded towards
          positive infinity.

     If OP is not given it defaults to `"fix"'.  An example
     demonstrating these rounding rules is

          idivide (int8 ([-3, 3]), int8 (4), "fix")
            => int8 ([0, 0])
          idivide (int8 ([-3, 3]), int8 (4), "round")
            => int8 ([-1, 1])
          idivide (int8 ([-3, 3]), int8 (4), "floor")
            => int8 ([-1, 0])
          idivide (int8 ([-3, 3]), int8 (4), "ceil")
            => int8 ([0, 1])

     *See also:* *note ldivide: doc-ldivide, *note rdivide: doc-rdivide.


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

4.5 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: C = bitset (A, N)
 -- Function File: C = bitset (A, N, VAL)
     Set or reset bit(s) N of unsigned integers in A.  VAL = 0 resets
     and VAL = 1 sets the bits.  The lowest significant bit is: N = 1

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

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

 -- Function File: C = 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:* *note bitand: doc-bitand, *note bitor: doc-bitor,
     *note bitxor: doc-bitxor, *note bitset: doc-bitset, *note bitcmp:
     doc-bitcmp, *note bitshift: doc-bitshift, *note bitmax: doc-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 value 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 ()
 -- Built-in Function:  bitmax ("double")
 -- Built-in Function:  bitmax ("single")
     Return the largest integer that can be represented within a
     floating point value.  The default class is "double", but "single"
     is a valid option.  On IEEE-754 compatible systems, `bitmax' is
     2^53 - 1.

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

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

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

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

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

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

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

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

   The bitwise 'not' operator is a unary operator that performs a
logical 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:* *note bitand: doc-bitand, *note bitor: doc-bitor,
     *note bitxor: doc-bitxor, *note bitset: doc-bitset, *note bitget:
     doc-bitget, *note bitcmp: doc-bitcmp, *note bitshift:
     doc-bitshift, *note bitmax: doc-bitmax.

   Octave also includes the ability to left-shift and right-shift
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 the 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:* *note bitand: doc-bitand, *note bitor: doc-bitor,
     *note bitxor: doc-bitxor, *note bitset: doc-bitset, *note bitget:
     doc-bitget, *note bitcmp: doc-bitcmp, *note bitmax: doc-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
kept 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: Promotion and Demotion of Data Types,  Prev: Bit Manipulations,  Up: Numeric Data Types

4.6 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 `!', which correspond
to "Logical And", "Logical Or", and "Logical Negation".  These
operations all follow the usual 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; 2 ]

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

   Logical values can also be constructed by casting numeric objects to
logical values, or by using the `true' or `false' functions.

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

     *See also:* *note double: doc-double, *note single: doc-single,
     *note char: doc-char.

 -- 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.  If invoked with a single scalar integer argument,
     return a square matrix of the specified size.  If invoked with two
     or more scalar integer arguments, or a vector of integer values,
     return an array with given dimensions.

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

 -- 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.  If invoked with a single scalar integer argument,
     return a square matrix of the specified size.  If invoked with two
     or more scalar integer arguments, or a vector of integer values,
     return an array with given dimensions.

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


File: octave.info,  Node: Promotion and Demotion of Data Types,  Next: Predicates for Numeric Objects,  Prev: Logical Values,  Up: Numeric Data Types

4.7 Promotion and Demotion of Data Types
========================================

Many operators and functions can work with mixed data types.  For
example,

     uint8 (1) + 1
         => 2

where the above operator works with an 8-bit integer and a double
precision value and returns an 8-bit integer value.  Note that the type
is demoted to an 8-bit integer, rather than promoted to a double
precision value as might be expected.  The reason is that if Octave
promoted values in expressions like the above with all numerical
constants would need to be explicitly cast to the appropriate data type
like

     uint8 (1) + uint8 (1)
         => 2

which becomes difficult for the user to apply uniformly and might allow
hard to find bugs to be introduced.  The same applies to single
precision values where a mixed operation such as

     single (1) + 1
         => 2

returns a single precision value.  The mixed operations that are valid
and their returned data types are

               Mixed Operation        Result                 
---------------------------------------------------------------------------- 
               double OP single       single                 
               double OP integer      integer                
               double OP char         double                 
               double OP logical      double                 
               single OP integer      integer                
               single OP char         single                 
               single OP logical      single                 

   The same logic applies to functions with mixed arguments such as

     min (single (1), 0)
        => 0

where the returned value is single precision.

   In the case of mixed type indexed assignments, the type is not
changed.  For example,

     x = ones (2, 2);
     x (1, 1) = single (2)
         => x = 2   1
                1   1

where `x' remains of the double precision type.


File: octave.info,  Node: Predicates for Numeric Objects,  Prev: Promotion and Demotion of Data Types,  Up: Numeric Data Types

4.8 Predicates for Numeric Objects
==================================

Since the type of a variable may change during the execution of a
program, it can be necessary to do type checking at run-time.  Doing
this also allows you to change the behavior 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 true if X is a numeric object, i.e., an integer, real, or
     complex array.  Logical and character arrays are not considered to
     be numeric.

     *See also:* *note isinteger: doc-isinteger, *note isfloat:
     doc-isfloat, *note isreal: doc-isreal, *note iscomplex:
     doc-iscomplex, *note islogical: doc-islogical, *note ischar:
     doc-ischar, *note iscell: doc-iscell, *note isstruct: doc-isstruct.

 -- Built-in Function:  isfloat (X)
     Return true if X is a floating-point numeric object.  Objects of
     class double or single are floating-point objects.

     *See also:* *note isinteger: doc-isinteger, *note ischar:
     doc-ischar, *note islogical: doc-islogical, *note isnumeric:
     doc-isnumeric, *note isa: doc-isa.

 -- Built-in Function:  isreal (X)
     Return true if X is a non-complex matrix or scalar.  For
     compatibility with MATLAB, this includes logical and character
     matrices.

     *See also:* *note iscomplex: doc-iscomplex, *note isnumeric:
     doc-isnumeric.

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

     *See also:* *note isreal: doc-isreal, *note isnumeric:
     doc-isnumeric.

 -- Built-in Function:  ismatrix (A)
     Return true if A is a numeric, logical, or character matrix.
     Scalars (1x1 matrices) and vectors (1xN or Nx1 matrices) are
     subsets of the more general N-dimensional matrix and `ismatrix'
     will return true for these objects as well.

     *See also:* *note isscalar: doc-isscalar, *note isvector:
     doc-isvector, *note iscell: doc-iscell, *note isstruct:
     doc-isstruct, *note issparse: doc-issparse.

 -- Function File:  isvector (X)
     Return true if X is a vector.  A vector is a 2-D array where one
     of the dimensions is equal to 1.  As a consequence a 1x1 array, or
     scalar, is also a vector.

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

 -- Function File:  isrow (X)
     Return true if X is a row vector.

     *See also:* *note iscolumn: doc-iscolumn, *note isscalar:
     doc-isscalar, *note isvector: doc-isvector, *note ismatrix:
     doc-ismatrix.

 -- Function File:  iscolumn (X)
     Return true if X is a column vector.

     *See also:* *note isrow: doc-isrow, *note isscalar: doc-isscalar,
     *note isvector: doc-isvector, *note ismatrix: doc-ismatrix.

 -- Function File:  isscalar (X)
     Return true if X is a scalar.

     *See also:* *note isvector: doc-isvector, *note ismatrix:
     doc-ismatrix.

 -- Function File:  issquare (X)
     Return true if X is a square matrix.

     *See also:* *note isscalar: doc-isscalar, *note isvector:
     doc-isvector, *note ismatrix: doc-ismatrix, *note size: doc-size.

 -- Function File:  issymmetric (X)
 -- Function File:  issymmetric (X, TOL)
     Return true if X is a symmetric matrix within the tolerance
     specified by TOL.  The default tolerance is zero (uses faster
     code).  Matrix X is considered symmetric if `norm (X - X.', Inf) /
     norm (X, Inf) < TOL'.

     *See also:* *note ishermitian: doc-ishermitian, *note isdefinite:
     doc-isdefinite.

 -- Function File:  ishermitian (X)
 -- Function File:  ishermitian (X, TOL)
     Return true if X is Hermitian within the tolerance specified by
     TOL.  The default tolerance is zero (uses faster code).  Matrix X
     is considered symmetric if `norm (X - X', Inf) / norm (X, Inf) <
     TOL'.

     *See also:* *note issymmetric: doc-issymmetric, *note isdefinite:
     doc-isdefinite.

 -- Function File:  isdefinite (X)
 -- 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 of `100
     * eps * norm (X, "fro")'

     *See also:* *note issymmetric: doc-issymmetric, *note ishermitian:
     doc-ishermitian.

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

     *See also:* *note isfloat: doc-isfloat, *note isinteger:
     doc-isinteger, *note ischar: doc-ischar, *note isnumeric:
     doc-isnumeric, *note isa: doc-isa.

 -- Function File:  isprime (X)
     Return a logical array which is true where the elements of X are
     prime numbers and false where they are not.

     If the maximum value in X is very large, then you should be using
     special purpose factorization code.

          isprime (1:6)
              => [0, 1, 1, 0, 1, 0]

     *See also:* *note primes: doc-primes, *note factor: doc-factor,
     *note gcd: doc-gcd, *note lcm: doc-lcm.

   If instead of knowing properties of variables, you wish to know which
variables are defined and to gather other information about the
workspace itself, see *note Status of Variables::.


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.

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

* Escape Sequences in String Constants::
* Character Arrays::
* Creating Strings::
* Comparing Strings::
* Manipulating Strings::
* String Conversions::
* Character Class Functions::


File: octave.info,  Node: Escape Sequences in String Constants,  Next: Character Arrays,  Up: Strings

5.1 Escape Sequences in String Constants
========================================

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 ]

   Here is a table of all the escape sequences used in Octave (within
double quoted strings).  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.


   In a single-quoted string there is only one escape sequence: you may
insert a single quote character using two single quote characters in
succession.  For example,

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

   In scripts the two different string types can be distinguished if
necessary by using `is_dq_string' and `is_sq_string'.

 -- Built-in Function:  is_dq_string (X)
     Return true if X is a double-quoted character string.

     *See also:* *note is_sq_string: doc-is_sq_string, *note ischar:
     doc-ischar.

 -- Built-in Function:  is_sq_string (X)
     Return true if X is a single-quoted character string.

     *See also:* *note is_dq_string: doc-is_dq_string, *note ischar:
     doc-ischar.


File: octave.info,  Node: Character Arrays,  Next: Creating Strings,  Prev: Escape Sequences in String Constants,  Up: Strings

5.2 Character Arrays
====================

The string representation used by Octave is an array of characters, so
internally the string "dddddddddd" is actually a row vector of length 10
containing the value 100 in all places (100 is the ASCII code of "d").
This lends itself to the obvious generalization 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.

   The function `ischar' can be used to test if an object is a character
matrix.

 -- Built-in Function:  ischar (X)
     Return true if X is a character array.

     *See also:* *note isfloat: doc-isfloat, *note isinteger:
     doc-isinteger, *note islogical: doc-islogical, *note isnumeric:
     doc-isnumeric, *note iscellstr: doc-iscellstr, *note isa: doc-isa.

   To test if an object is a string (i.e., a character vector and not a
character matrix) you can use the `ischar' function in combination with
the `isvector' function as in the following example:

     ischar(collection)
          => ans = 1

     ischar(collection) && isvector(collection)
          => ans = 0

     ischar("my string") && isvector("my string")
          => ans = 1

   One relevant question is, what happens when a 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.  It is possible to use a different character than the blank
character using the `string_fill_char' function.

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

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

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


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

5.3 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, for example:

          blanks (10);
          whos ans;
               =>
                Attr Name        Size                     Bytes  Class
                ==== ====        ====                     =====  =====
                     ans         1x10                        10  char

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

* Menu:

* Concatenating Strings::
* Conversion of Numerical Data to Strings::


File: octave.info,  Node: Concatenating Strings,  Next: Conversion of Numerical Data to Strings,  Up: Creating Strings

5.3.1 Concatenating Strings
---------------------------

It has been shown above that strings can be concatenated using matrix
notation (*note Strings::, *note Character Arrays::).  Apart from that,
there are several functions to concatenate string objects: `char',
`strvcat', `strcat' and `cstrcat'.  In addition, the general purpose
concatenation functions can be used: see *note cat: doc-cat, *note
horzcat: doc-horzcat. and *note vertcat: doc-vertcat.

   * All string concatenation functions except `cstrcat' convert
     numerical input into character data by taking the corresponding
     ASCII character for each element, as in the following example:

          char([98, 97, 110, 97, 110, 97])
               => ans =
                 banana

   * `char' and `strvcat' concatenate vertically, while `strcat' and
     `cstrcat' concatenate horizontally.  For example:

          char("an apple", "two pears")
               => ans =
                 an apple
                 two pears

          strcat("oc", "tave", " is", " good", " for you")
               => ans =
                 octave is good for you

   * `char' generates an empty row in the output for each empty string
     in the input.  `strvcat', on the other hand, eliminates empty
     strings.

          char("orange", "green", "", "red")
               => ans =
                 orange
                 green

                 red

          strvcat("orange", "green", "", "red")
               => ans =
                 orange
                 green
                 red

   * All string concatenation functions except `cstrcat' also accept
     cell array data (*note Cell Arrays::).  `char' and `strvcat'
     convert cell arrays into character arrays, while `strcat'
     concatenates within the cells of the cell arrays:

          char({"red", "green", "", "blue"})
               => ans =
                 red
                 green

                 blue

          strcat({"abc"; "ghi"}, {"def"; "jkl"})
               => ans =
                 {
                   [1,1] = abcdef
                   [2,1] = ghijkl
                 }

   * `strcat' removes trailing white space in the arguments (except
     within cell arrays), while `cstrcat' leaves white space untouched.
     Both kinds of behavior can be useful as can be seen in the
     examples:

          strcat(["dir1";"directory2"], ["/";"/"], ["file1";"file2"])
               => ans =
                 dir1/file1
                 directory2/file2

          cstrcat(["thirteen apples"; "a banana"], [" 5$";" 1$"])
               => ans =
                 thirteen apples 5$
                 a banana        1$

     Note that in the above example for `cstrcat', the white space
     originates from the internal representation of the strings in a
     string array (*note Character Arrays::).

 -- Built-in Function:  char (X)
 -- Built-in Function:  char (X, ...)
 -- Built-in Function:  char (S1, S2, ...)
 -- Built-in Function:  char (CELL_ARRAY)
     Create a string array from one or more numeric matrices, character
     matrices, or cell arrays.  Arguments are concatenated vertically.
     The returned values are padded with blanks as needed to make each
     row of the string array have the same length.  Empty input strings
     are significant and will concatenated in the output.

     For numerical input, each element is converted to the
     corresponding ASCII character.  A range error results if an input
     is outside the ASCII range (0-255).

     For cell arrays, each element is concatenated separately.  Cell
     arrays converted through `char' can mostly be converted back with
     `cellstr'.  For example:

          char ([97, 98, 99], "", {"98", "99", 100}, "str1", ["ha", "lf"])
               => ["abc    "
                   "       "
                   "98     "
                   "99     "
                   "d      "
                   "str1   "
                   "half   "]

     *See also:* *note strvcat: doc-strvcat, *note cellstr: doc-cellstr.

 -- Built-in Function:  strvcat (X)
 -- Built-in Function:  strvcat (X, ...)
 -- Built-in Function:  strvcat (S1, S2, ...)
 -- Built-in Function:  strvcat (CELL_ARRAY)
     Create a character array from one or more numeric matrices,
     character matrices, or cell arrays.  Arguments are concatenated
     vertically.  The returned values are padded with blanks as needed
     to make each row of the string array have the same length.  Unlike
     `char', empty strings are removed and will not appear in the
     output.

     For numerical input, each element is converted to the
     corresponding ASCII character.  A range error results if an input
     is outside the ASCII range (0-255).

     For cell arrays, each element is concatenated separately.  Cell
     arrays converted through `strvcat' can mostly be converted back
     with `cellstr'.  For example:

          strvcat ([97, 98, 99], "", {"98", "99", 100}, "str1", ["ha", "lf"])
               => ["abc    "
                   "98     "
                   "99     "
                   "d      "
                   "str1   "
                   "half   "]

     *See also:* *note char: doc-char, *note strcat: doc-strcat, *note
     cstrcat: doc-cstrcat.

 -- Function File:  strcat (S1, S2, ...)
     Return a string containing all the arguments concatenated
     horizontally.  If the arguments are cells strings,  `strcat'
     returns a cell string with the individual cells concatenated.  For
     numerical input, each element is converted to the corresponding
     ASCII character.  Trailing white space is eliminated.  For example:

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

          s = { "ab"; "cde" };
          strcat (s, s, s)
              =>
                  {
                    [1,1] = ababab
                    [2,1] = cdecdecde
                  }

     *See also:* *note cstrcat: doc-cstrcat, *note char: doc-char,
     *note strvcat: doc-strvcat.

 -- Function File:  cstrcat (S1, S2, ...)
     Return a string containing all the arguments concatenated
     horizontally.  Trailing white space is preserved.  For example:

          cstrcat ("ab   ", "cd")
                => "ab   cd"

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

     *See also:* *note strcat: doc-strcat, *note char: doc-char, *note
     strvcat: doc-strvcat.


File: octave.info,  Node: Conversion of Numerical Data to Strings,  Prev: Concatenating Strings,  Up: Creating Strings

5.3.2 Conversion of Numerical Data to Strings
---------------------------------------------

Apart from the string concatenation functions (*note Concatenating
Strings::) which cast numerical data to the corresponding ASCII
characters, there are several functions that format numerical data as
strings.  `mat2str' and `num2str' convert real or complex matrices,
while `int2str' converts integer matrices.  `int2str' takes the real
part of complex values and round fractional values to integer.  A more
flexible way to format numerical data as strings is the `sprintf'
function (*note Formatted Output::, *note doc-sprintf::).

 -- Function File: S = mat2str (X, N)
 -- Function File: S = mat2str (X, N, "class")
     Format real, complex, and logical matrices as strings.  The
     returned string may be used to reconstruct the original matrix by
     using 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 15.

     If the argument "class" is given then the class of X is included
     in the string in such a way that `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])"

          mat2str (logical (eye (2)))
               => "[true false;false true]"

          isequal (x, eval (mat2str (x)))
               => 1

     *See also:* *note sprintf: doc-sprintf, *note num2str:
     doc-num2str, *note int2str: doc-int2str.

 -- Function File:  num2str (X)
 -- Function File:  num2str (X, PRECISION)
 -- Function File:  num2str (X, FORMAT)
     Convert a number (or array) to a string (or a character array).
     The optional second argument may either give the number of
     significant digits (PRECISION) to be used in the output or a format
     template string (FORMAT) as in `sprintf' (*note Formatted
     Output::).  `num2str' can also handle complex numbers.  For
     example:

          num2str (123.456)
               => "123.46"

          num2str (123.456, 4)
               => "123.5"

          s = num2str ([1, 1.34; 3, 3.56], "%5.1f")
               => s =
                  1.0  1.3
                  3.0  3.6
          whos s
               =>
                Attr Name        Size                     Bytes  Class
                ==== ====        ====                     =====  =====
                     s           2x8                         16  char

          num2str (1.234 + 27.3i)
               => "1.234+27.3i"

     The `num2str' function is not very flexible.  For better control
     over the results, use `sprintf' (*note Formatted Output::).  Note
     that for complex X, the format string may only contain one output
     conversion specification and nothing else.  Otherwise, you will
     get unpredictable results.

     *See also:* *note sprintf: doc-sprintf, *note int2str:
     doc-int2str, *note mat2str: doc-mat2str.

 -- Function File:  int2str (N)
     Convert an integer (or array of integers) to a string (or a
     character array).

          int2str (123)
               => "123"

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

          whos s
               => s =
                Attr Name        Size                     Bytes  Class
                ==== ====        ====                     =====  =====
                     s           2x7                         14  char

     This function is not very flexible.  For better control over the
     results, use `sprintf' (*note Formatted Output::).

     *See also:* *note sprintf: doc-sprintf, *note num2str:
     doc-num2str, *note mat2str: doc-mat2str.


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

5.4 Comparing Strings
=====================

Since a string is a character array, comparisons 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 strings are identical it is necessary to use the
`strcmp' function.  It compares complete strings and is case sensitive.
`strncmp' compares only the first `N' characters (with `N' given as a
parameter).  `strcmpi' and `strncmpi' are the corresponding functions
for case-insensitive comparison.

 -- 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:* *note strcmpi: doc-strcmpi, *note strncmp:
     doc-strncmp, *note strncmpi: doc-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:* *note strncmpi: doc-strncmpi, *note strcmp:
     doc-strcmp, *note strcmpi: doc-strcmpi.

 -- Built-in Function:  strcmpi (S1, S2)
     Return 1 if the character strings S1 and S2 are the same,
     disregarding case of alphabetic characters, 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.

     *Caution:* National alphabets are not supported.

     *See also:* *note strcmp: doc-strcmp, *note strncmp: doc-strncmp,
     *note strncmpi: doc-strncmpi.

 -- Built-in Function:  strncmpi (S1, S2, N)
     Return 1 if the first N character of S1 and S2 are the same,
     disregarding case of alphabetic characters, 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.

     *Caution:* National alphabets are not supported.

     *See also:* *note strncmp: doc-strncmp, *note strcmp: doc-strcmp,
     *note strcmpi: doc-strcmpi.

 -- Function File: VALIDSTR = validatestring (STR, STRARRAY)
 -- Function File: VALIDSTR = validatestring (STR, STRARRAY, FUNCNAME)
 -- Function File: VALIDSTR = validatestring (STR, STRARRAY, FUNCNAME,
          VARNAME)
 -- Function File: VALIDSTR = validatestring (..., POSITION)
     Verify that STR is an element, or substring of an element, in
     STRARRAY.

     When STR is a character string to be tested, and STRARRAY is a
     cellstr of valid values, then VALIDSTR will be the validated form
     of STR where validation is defined as STR being a member or
     substring of VALIDSTR.  This is useful for both verifying and
     expanding short options, such as "r", to their longer forms, such
     as "red".  If STR is a substring of VALIDSTR, and there are
     multiple matches, the shortest match will be returned if all
     matches are substrings of each other.  Otherwise, an error will be
     raised because the expansion of STR is ambiguous.  All comparisons
     are case insensitive.

     The additional inputs FUNCNAME, VARNAME, and POSITION are optional
     and will make any generated validation error message more specific.

     Examples:

          validatestring ("r", {"red", "green", "blue"})
          => "red"

          validatestring ("b", {"red", "green", "blue", "black"})
          => error: validatestring: multiple unique matches were found for 'b':
             blue, black

     *See also:* *note strcmp: doc-strcmp, *note strcmpi: doc-strcmpi.


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

5.5 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 whitespace 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 of strings, operate recursively on each string element.

     Examples:

          deblank ("    abc  ")
               =>  "    abc"

          deblank ([" abc   "; "   def   "])
               =>  [" abc  " ; "   def"]

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

 -- Function File:  strtrim (S)
     Remove leading and trailing whitespace from S.  If S is a matrix,
     STRTRIM trims each row to the length of longest string.  If S is a
     cell array of strings, operate recursively on each string element.
     For example:

          strtrim ("    abc  ")
               =>  "abc"

          strtrim ([" abc   "; "   def   "])
               =>  ["abc  "  ; "  def"]

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

 -- Function File:  strtrunc (S, N)
     Truncate the character string S to length N.  If S is a character
     matrix, then the number of columns is adjusted.  If S is a cell
     array of strings, then the operation is performed on each cell
     element and the new cell array is returned.

 -- Function File:  findstr (S, T)
 -- 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 true, 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]

     *Caution:* `findstr' is scheduled for deprecation.  Use `strfind'
     in all new code.

     *See also:* *note strfind: doc-strfind, *note strmatch:
     doc-strmatch, *note strcmp: doc-strcmp, *note strncmp:
     doc-strncmp, *note strcmpi: doc-strcmpi, *note strncmpi:
     doc-strncmpi, *note find: doc-find.

 -- Function File: IDX = strchr (STR, CHARS)
 -- Function File: IDX = strchr (STR, CHARS, N)
 -- Function File: IDX = strchr (STR, CHARS, N, DIRECTION)
 -- Function File: [I, J] = strchr (...)
     Search for the string STR for occurrences of characters from the
     set CHARS.  The return value(s), as well as the N and DIRECTION
     arguments behave identically as in `find'.

     This will be faster than using regexp in most cases.

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

 -- 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.  S may also be a string
     array or cell array of strings.

     For example:

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

     If DIRECTION is `"first"', return the first element found.  If
     DIRECTION is `"last"', return the last element found.

     *See also:* *note find: doc-find, *note rindex: doc-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.  S
     may also be a string array or cell array of strings.

     For example:

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

     The `rindex' function is equivalent to `index' with DIRECTION set
     to `"last"'.

     *See also:* *note find: doc-find, *note index: doc-index.

 -- Loadable Function: IDX = strfind (STR, PATTERN)
 -- Loadable Function: 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 a cell array of strings CELLSTR is specified then IDX is a cell
     array of vectors, as specified above.  Examples:

          strfind ("abababa", "aba")
               => [1, 3, 5]

          strfind ({"abababa", "bebebe", "ab"}, "aba")
               => ans =
                  {
                    [1,1] =

                       1   3   5

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

     *See also:* *note findstr: doc-findstr, *note strmatch:
     doc-strmatch, *note regexp: doc-regexp, *note regexpi:
     doc-regexpi, *note find: doc-find.

 -- Function File:  strmatch (S, A)
 -- Function File:  strmatch (S, A, "exact")
     Return indices of entries of A which begin with the string S.  The
     second argument A must be a string, character 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.  Trailing
     spaces and nulls in S and A are ignored when matching.  option.

     For example:

          strmatch ("apple", "apple juice")
               => 1

          strmatch ("apple", ["apple  "; "apple juice"; "an apple"])
               => [1; 2]

          strmatch ("apple", ["apple  "; "apple juice"; "an apple"], "exact")
               => [1]

     *Caution:* `strmatch' is scheduled for deprecation.  Use `strcmpi'
     or `strncmpi' in all new code.

     *See also:* *note strfind: doc-strfind, *note findstr:
     doc-findstr, *note strcmp: doc-strcmp, *note strncmp: doc-strncmp,
     *note strcmpi: doc-strcmpi, *note strncmpi: doc-strncmpi, *note
     find: doc-find.

 -- Function File: [TOK, REM] = strtok (STR)
 -- Function File: [TOK, REM] = strtok (STR, DELIM)
     Find all characters in the string STR 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 delimiter.  Leading delimiters are ignored.  If DELIM is
     not specified, whitespace is assumed.  STR may also be a cell
     array of strings in which case the function executes on every
     individual string and returns a cell array of tokens and
     remainders.

     Examples:

          strtok ("this is the life")
               => "this"

          [tok, rem] = strtok ("14*27+31", "+-*/")
               =>
                  tok = 14
                  rem = *27+31

     *See also:* *note index: doc-index, *note strsplit: doc-strsplit,
     *note strchr: doc-strchr, *note isspace: doc-isspace.

 -- Function File: [CSTR] = strsplit (S, SEP)
 -- Function File: [CSTR] = strsplit (S, SEP, STRIP_EMPTY)
     Split the string S using one or more separators SEP and return a
     cell array of strings.  Consecutive separators and separators at
     boundaries result in empty strings, unless STRIP_EMPTY is true.
     The default value of STRIP_EMPTY is false.

     2-D character arrays are split at separators and at the original
     column boundaries.

     Example:

          strsplit ("a,b,c", ",")
                =>
                    {
                      [1,1] = a
                      [1,2] = b
                      [1,3] = c
                    }

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

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

 -- Function File: [A, ...] = strread (STR)
 -- Function File: [A, ...] = strread (STR, FORMAT)
 -- Function File: [A, ...] = strread (STR, FORMAT, FORMAT_REPEAT)
 -- Function File: [A, ...] = strread (STR, FORMAT, PROP1, VALUE1, ...)
 -- Function File: [A, ...] = strread (STR, FORMAT, FORMAT_REPEAT,
          PROP1, VALUE1, ...)
     Read data from a string.

     The string STR is split into words that are repeatedly matched to
     the specifiers in FORMAT.  The first word is matched to the first
     specifier, the second to the second specifier and so forth.  If
     there are more words than specifiers, the process is repeated
     until all words have been processed.

     The string FORMAT describes how the words in STR should be parsed.
     It may contain any combination of the following specifiers:

    `%s'
          The word is parsed as a string.

    `%f'
    `%n'
          The word is parsed as a number and converted to double.

    `%d'
    `%u'
          The word is parsed as a number and converted to int32.

    `%*', '%*f', '%*s'
          The word is skipped.

          For %s and %d, %f, %n, %u and the associated %*s ...
          specifiers an optional width can be specified as %Ns, etc.
          where N is an integer > 1.  For %f, format specifiers like
          %N.Mf are allowed.

    `literals'
          In addition the format may contain literal character strings;
          these will be skipped during reading.

     Parsed word corresponding to the first specifier are returned in
     the first output argument and likewise for the rest of the
     specifiers.

     By default, FORMAT is "%f", meaning that numbers are read from
     STR.  This will do if STR contains only numeric fields.

     For example, the string

          STR = "\
          Bunny Bugs   5.5\n\
          Duck Daffy  -7.5e-5\n\
          Penguin Tux   6"

     can be read using

          [A, B, C] = strread (STR, "%s %s %f");

     Optional numeric argument FORMAT_REPEAT can be used for limiting
     the number of items read:

    -1
          (default) read all of the string until the end.

    N
          Read N times NARGOUT items.  0 (zero) is an acceptable value
          for FORMAT_REPEAT.

     The behavior of `strread' can be changed via property-value pairs.
     The following properties are recognized:

    "commentstyle"
          Parts of STR are considered comments and will be skipped.
          VALUE is the comment style and can be any of the following.
             * "shell" Everything from `#' characters to the nearest
               end-of-line is skipped.

             * "c" Everything between `/*' and `*/' is skipped.

             * "c++" Everything from `//' characters to the nearest
               end-of-line is skipped.

             * "matlab" Everything from `%' characters to the nearest
               end-of-line is skipped.

             * user-supplied.  Two options: (1) One string, or 1x1 cell
               string: Skip everything to the right of it; (2) 2x1 cell
               string array: Everything between the left and right
               strings is skipped.

    "delimiter"
          Any character in VALUE will be used to split STR into words
          (default value = any whitespace).

    "emptyvalue":
          Value to return for empty numeric values in non-whitespace
          delimited data.  The default is NaN.  When the data type does
          not support NaN (int32 for example), then default is zero.

    "multipledelimsasone"
          Treat a series of consecutive delimiters, without whitespace
          in between, as a single delimiter.  Consecutive delimiter
          series need not be vertically "aligned".

    "treatasempty"
          Treat single occurrences (surrounded by delimiters or
          whitespace) of the string(s) in VALUE as missing values.

    "returnonerror"
          If VALUE true (1, default), ignore read errors and return
          normally.  If false (0), return an error.

    "whitespace"
          Any character in VALUE will be interpreted as whitespace and
          trimmed; the string defining whitespace must be enclosed in
          double quotes for proper processing of special characters
          like \t.  The default value for whitespace = " \b\r\n\t"
          (note the space).  Unless whitespace is set to " (empty) AND
          at least one "%s" format conversion specifier is supplied, a
          space is always part of whitespace.


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

 -- Loadable Function:  strrep (S, PTN, REP)
 -- Loadable Function:  strrep (S, PTN, REP, "overlaps", O)
     Replace all occurrences of the substring PTN in the string S with
     the string REP and return the result.  For example:

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

     S may also be a cell array of strings, in which case the
     replacement is done for each element and a cell array is returned.

     *See also:* *note regexprep: doc-regexprep, *note strfind:
     doc-strfind, *note findstr: doc-findstr.

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

     Position numbering for offsets begins with 1.  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.  A
     negative value for LEN extracts to within LEN characters of the
     end of the string

     Examples:

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

     This function is patterned after the equivalent function in Perl.

 -- Loadable Function: [S, E, TE, M, T, NM] = regexp (STR, PAT)
 -- Loadable Function: [...] = regexp (STR, PAT, "OPT1", ...)
     Regular expression string matching.  Search for PAT in STR and
     return the positions and substrings of any matches, 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

         `{N}'
               Match exactly N times

         `{N,}'
               Match N or more times

         `{M,N}'
               Match between M and N times

    `[...] [^...]'
          List operators.  The pattern will match any character listed
          between "[" and "]".  If the first character is "^" then the
          pattern is inverted and any character except those listed
          between brackets will match.

          Escape sequences defined below can also be used inside list
          operators.  For example, a template for a floating point
          number might be `[-+.\d]+'.

    `()'
          Grouping operator

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

    `^ $'
          Anchoring operators.  Requires pattern to occur at the start
          (`^') or end (`$') of the string.

     In addition, the following escaped characters have special
     meaning.  Note, 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'
          Match any word character

    `\W'
          Match any non-word character

    `\<'
          Match the beginning of a word

    `\>'
          Match the end of a word

    `\s'
          Match any whitespace character

    `\S'
          Match any non-whitespace character

    `\d'
          Match any digit

    `\D'
          Match any non-digit

     The outputs of `regexp' default to the order given below

    S
          The start indices of each matching substring

    E
          The end indices of each matching substring

    TE
          The extents of each 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 by `(?<name>...)'.

    SP
          A cell array of the text not returned by match.

     Particular output arguments, or the order of the output arguments,
     can be selected by additional OPT 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                   
                   'split'              SP                   

     Additional arguments are summarized below.

    `once'
          Return only the first occurrence of the pattern.

    `matchcase'
          Make the matching case sensitive.  (default)

          Alternatively, use (?-i) in the pattern.

    `ignorecase'
          Ignore case when matching the pattern to the string.

          Alternatively, use (?i) in the pattern.

    `stringanchors'
          Match the anchor characters at the beginning and end of the
          string.  (default)

          Alternatively, use (?-m) in the pattern.

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

          Alternatively, use (?m) in the pattern.

    `dotall'
          The pattern `.' matches all characters including the newline
          character.   (default)

          Alternatively, use (?s) in the pattern.

    `dotexceptnewline'
          The pattern `.' matches all characters except the newline
          character.

          Alternatively, use (?-s) in the pattern.

    `literalspacing'
          All characters in the pattern, including whitespace, are
          significant and are used in pattern matching.  (default)

          Alternatively, use (?-x) in the pattern.

    `freespacing'
          The pattern may include arbitrary whitespace and also
          comments beginning with the character `#'.

          Alternatively, use (?x) in the pattern.


     *See also:* *note regexpi: doc-regexpi, *note strfind:
     doc-strfind, *note regexprep: doc-regexprep.

 -- Loadable Function: [S, E, TE, M, T, NM] = regexpi (STR, PAT)
 -- Loadable Function: [...] = regexpi (STR, PAT, "OPT1", ...)
     Case insensitive regular expression string matching.  Search for
     PAT in STR and return the positions and substrings of any matches,
     or empty values if there are none.  *Note regexp: doc-regexp, for
     details on the syntax of the search pattern.

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

 -- Loadable Function: OUTSTR = regexprep (STRING, PAT, REPSTR)
 -- Loadable Function: OUTSTR = regexprep (STRING, PAT, REPSTR, "OPT1",
          ...)
     Replace occurrences of pattern PAT in STRING with REPSTR.

     The pattern is a regular expression as documented for `regexp'.
     *Note regexp: doc-regexp.

     The replacement string may contain `$i', which substitutes for the
     ith set of parentheses in the match string.  For example,

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

     returns "Dunn, Bill"

     Options in addition to those of `regexp' are

    `once'
          Replace only the first occurrence of PAT in the result.

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


     *See also:* *note regexp: doc-regexp, *note regexpi: doc-regexpi,
     *note strrep: doc-strrep.

 -- Function File:  regexptranslate (OP, S)
     Translate a string for use in a regular expression.  This may
     include either wildcard replacement or special character escaping.
     The behavior is controlled by OP which can take the following
     values

    "wildcard"
          The wildcard characters `.', `*', and `?' are replaced with
          wildcards that are appropriate for a regular expression.  For
          example:

               regexptranslate ("wildcard", "*.m")
                    => ".*\.m"

    "escape"
          The characters `$.?[]', that have special meaning for regular
          expressions are escaped so that they are treated literally.
          For example:

               regexptranslate ("escape", "12.5")
                    => "12\.5"


     *See also:* *note regexp: doc-regexp, *note regexpi: doc-regexpi,
     *note regexprep: doc-regexprep.

 -- Function File:  untabify (T)
 -- Function File:  untabify (T, TW)
 -- Function File:  untabify (T, TW, DEBLANK)
     Replace TAB characters in T, with spaces.  The tab width is
     specified by TW, or defaults to eight.  The input, T, may be
     either a 2-D character array, or a cell array of character
     strings.  The output is the same class as the input.

     If the optional argument DEBLANK is true, then the spaces will be
     removed from the end of the character data.

     The following example reads a file and writes an untabified version
     of the same file with trailing spaces stripped.

          fid = fopen ("tabbed_script.m");
          text = char (fread (fid, "uchar")');
          fclose (fid);
          fid = fopen ("untabified_script.m", "w");
          text = untabify (strsplit (text, "\n"), 8, true);
          fprintf (fid, "%s\n", text{:});
          fclose (fid);

     *See also:* *note strjust: doc-strjust, *note strsplit:
     doc-strsplit, *note deblank: doc-deblank.


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

5.6 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
     represented by the string S.  For example:

          bin2dec ("1110")
               => 14

     Spaces are ignored during conversion and may be used to make the
     binary number more readable.

          bin2dec ("1000 0001")
               => 129

     If S is a string matrix, return a column vector with one converted
     number per row of S; Invalid rows evaluate to NaN.

     If S is a cell array of strings, return a column vector with one
     converted number per cell element in S.

     *See also:* *note dec2bin: doc-dec2bin, *note base2dec:
     doc-base2dec, *note hex2dec: doc-hex2dec.

 -- Function File:  dec2bin (D, LEN)
     Return a binary number corresponding to the non-negative integer
     D, as a string of ones and zeros.  For example:

          dec2bin (14)
               => "1110"

     If D is a matrix or cell array, return a string matrix with one
     row per element in D, 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:* *note bin2dec: doc-bin2dec, *note dec2base:
     doc-dec2base, *note dec2hex: doc-dec2hex.

 -- Function File:  dec2hex (D, LEN)
     Return the hexadecimal string corresponding to the non-negative
     integer D.  For example:

          dec2hex (2748)
               => "ABC"

     If D is a matrix or cell array, return a string matrix with one
     row per element in D, 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:* *note hex2dec: doc-hex2dec, *note dec2base:
     doc-dec2base, *note dec2bin: doc-dec2bin.

 -- Function File:  hex2dec (S)
     Return the integer corresponding to the hexadecimal number
     represented by the string S.  For example:

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

     If S is a string matrix, return a column vector with one converted
     number per row of S; Invalid rows evaluate to NaN.

     If S is a cell array of strings, return a column vector with one
     converted number per cell element in S.

     *See also:* *note dec2hex: doc-dec2hex, *note base2dec:
     doc-base2dec, *note bin2dec: doc-bin2dec.

 -- Function File:  dec2base (D, BASE)
 -- Function File:  dec2base (D, BASE, LEN)
     Return a string of symbols in base BASE corresponding to the
     non-negative integer D.

          dec2base (123, 3)
             => "11120"

     If D is a matrix or cell array, return a string matrix with one
     row per element in D, padded with leading zeros to the width of
     the largest value.

     If BASE is a string then the characters of BASE are used as the
     symbols for the digits of D.  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:* *note base2dec: doc-base2dec, *note dec2bin:
     doc-dec2bin, *note dec2hex: doc-dec2hex.

 -- Function File:  base2dec (S, BASE)
     Convert S from a string of digits in base BASE to a decimal
     integer (base 10).

          base2dec ("11120", 3)
             => 123

     If S is a string matrix, return a column vector with one value per
     row of S.  If a row contains invalid symbols then the
     corresponding value will be NaN.

     If S is a cell array of strings, return a column vector with one
     value per cell element in S.

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

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

     *See also:* *note dec2base: doc-dec2base, *note bin2dec:
     doc-bin2dec, *note hex2dec: doc-hex2dec.

 -- Loadable Function: S = num2hex (N)
     Typecast a double precision number or vector to a 16 character
     hexadecimal string of the IEEE 754 representation of the number.
     For example:

          num2hex ([-1, 1, e, Inf, NaN, NA]);
          => "bff0000000000000
              3ff0000000000000
              4005bf0a8b145769
              7ff0000000000000
              fff8000000000000
              7ff00000000007a2"

     *See also:* *note hex2num: doc-hex2num, *note hex2dec:
     doc-hex2dec, *note dec2hex: doc-dec2hex.

 -- Loadable Function: N = hex2num (S)
     Typecast the 16 character hexadecimal character string to an IEEE
     754 double precision number.  If fewer than 16 characters are
     given the strings are right padded with '0' characters.

     Given a string matrix, `hex2num' treats each row as a separate
     number.

          hex2num (["4005bf0a8b145769";"4024000000000000"])
          => [2.7183; 10.000]

     *See also:* *note num2hex: doc-num2hex, *note hex2dec:
     doc-hex2dec, *note dec2hex: doc-dec2hex.

 -- Built-in Function:  str2double (S)
     Convert a string to a real or complex number.

     The string must be in one of the following formats where a and b
     are real numbers and the complex unit is 'i' or 'j':

        * a + bi

        * a + b*i

        * a + i*b

        * bi + a

        * b*i + a

        * i*b + a

     If present, a and/or b are of the form [+-]d[,.]d[[eE][+-]d] where
     the brackets indicate optional arguments and 'd' indicates zero or
     more digits.  The special input values `Inf', `NaN', and `NA' are
     also accepted.

     S may also be a character matrix, in which case the conversion is
     repeated for each row.  Or S may be a cell array of strings, in
     which case each element is converted and an array of the same
     dimensions is returned.

     `str2double' returns NaN for elements of S which cannot be
     converted.

     `str2double' can replace `str2num', and it avoids the security
     risk of using `eval' on unknown data.

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

 -- Function File:  strjust (S)
 -- Function File:  strjust (S, POS)
     Return the text, S, justified according to POS, which may be
     `"left"', `"center"', or `"right"'.  If POS is omitted it defaults
     to `"right"'.

     Null characters are replaced by spaces.  All other character data
     are treated as non-white space.

     Example:

          strjust (["a"; "ab"; "abc"; "abcd"])
               =>
                  "   a"
                  "  ab"
                  " abc"
                  "abcd"

     *See also:* *note deblank: doc-deblank, *note strrep: doc-strrep,
     *note strtrim: doc-strtrim, *note untabify: doc-untabify.

 -- Function File: X = str2num (S)
 -- Function File: [X, STATE] = str2num (S)
     Convert the string (or character array) S to a number (or an
     array).  Examples:

          str2num ("3.141596")
                => 3.141596

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

     The optional second output, STATE, is logically true when the
     conversion is successful.  If the conversion fails the numeric
     output, X, is empty and STATE is false.

     *Caution:* As `str2num' uses the `eval' function to do the
     conversion, `str2num' will execute any code contained in the
     string S.  Use `str2double' for a safer and faster conversion.

     For cell array of strings use `str2double'.

     *See also:* *note str2double: doc-str2double, *note eval: doc-eval.

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

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


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

 -- Mapping Function:  tolower (S)
 -- Mapping Function:  lower (S)
     Return a copy of the string or cell string S, with each uppercase
     character replaced by the corresponding lowercase one;
     non-alphabetic characters are left unchanged.  For example:

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

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

 -- Mapping Function:  toupper (S)
 -- Mapping Function:  upper (S)
     Return a copy of the string or cell string S, with each lowercase
     character replaced by the corresponding uppercase one;
     non-alphabetic characters are left unchanged.  For example:

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

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

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

 -- Built-in Function:  undo_string_escapes (S)
     Convert 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.7 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 a logical array which is true where the elements of S are
     letters or digits and false where they are not.  This is
     equivalent to (`isalpha (S) | isdigit (S)').

     *See also:* *note isalpha: doc-isalpha, *note isdigit:
     doc-isdigit, *note ispunct: doc-ispunct, *note isspace:
     doc-isspace, *note iscntrl: doc-iscntrl.

 -- Mapping Function:  isalpha (S)
     Return a logical array which is true where the elements of S are
     letters and false where they are not.  This is equivalent to
     (`islower (S) | isupper (S)').

     *See also:* *note isdigit: doc-isdigit, *note ispunct:
     doc-ispunct, *note isspace: doc-isspace, *note iscntrl:
     doc-iscntrl, *note isalnum: doc-isalnum, *note islower:
     doc-islower, *note isupper: doc-isupper.

 -- Function File:  isletter (S)
     Return a logical array which is true where the elements of S are
     letters and false where they are not.  This is an alias for the
     `isalpha' function.

     *See also:* *note isalpha: doc-isalpha, *note isdigit:
     doc-isdigit, *note ispunct: doc-ispunct, *note isspace:
     doc-isspace, *note iscntrl: doc-iscntrl, *note isalnum:
     doc-isalnum.

 -- Mapping Function:  islower (S)
     Return a logical array which is true where the elements of S are
     lowercase letters and false where they are not.

     *See also:* *note isupper: doc-isupper, *note isalpha:
     doc-isalpha, *note isletter: doc-isletter, *note isalnum:
     doc-isalnum.

 -- Mapping Function:  isupper (S)
     Return a logical array which is true where the elements of S are
     uppercase letters and false where they are not.

     *See also:* *note islower: doc-islower, *note isalpha:
     doc-isalpha, *note isletter: doc-isletter, *note isalnum:
     doc-isalnum.

 -- Mapping Function:  isdigit (S)
     Return a logical array which is true where the elements of S are
     decimal digits (0-9) and false where they are not.

     *See also:* *note isxdigit: doc-isxdigit, *note isalpha:
     doc-isalpha, *note isletter: doc-isletter, *note ispunct:
     doc-ispunct, *note isspace: doc-isspace, *note iscntrl:
     doc-iscntrl.

 -- Mapping Function:  isxdigit (S)
     Return a logical array which is true where the elements of S are
     hexadecimal digits (0-9 and a-fA-F).

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

 -- Mapping Function:  ispunct (S)
     Return a logical array which is true where the elements of S are
     punctuation characters and false where they are not.

     *See also:* *note isalpha: doc-isalpha, *note isdigit:
     doc-isdigit, *note isspace: doc-isspace, *note iscntrl:
     doc-iscntrl.

 -- Mapping Function:  isspace (S)
     Return a logical array which is true where the elements of S are
     whitespace characters (space, formfeed, newline, carriage return,
     tab, and vertical tab) and false where they are not.

     *See also:* *note iscntrl: doc-iscntrl, *note ispunct:
     doc-ispunct, *note isalpha: doc-isalpha, *note isdigit:
     doc-isdigit.

 -- Mapping Function:  iscntrl (S)
     Return a logical array which is true where the elements of S are
     control characters and false where they are not.

     *See also:* *note ispunct: doc-ispunct, *note isspace:
     doc-isspace, *note isalpha: doc-isalpha, *note isdigit:
     doc-isdigit.

 -- Mapping Function:  isgraph (S)
     Return a logical array which is true where the elements of S are
     printable characters (but not the space character) and false where
     they are not.

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

 -- Mapping Function:  isprint (S)
     Return a logical array which is true where the elements of S are
     printable characters (including the space character) and false
     where they are not.

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

 -- Mapping Function:  isascii (S)
     Return a logical array which is true where the elements of S are
     ASCII characters (in the range 0 to 127 decimal) and false where
     they are not.

 -- Function File:  isstrprop (STR, PROP)
     Test character string properties.  For example:

          isstrprop ("abc123", "alpha")
          => [1, 1, 1, 0, 0, 0]

     If STR is a cell array, `isstrpop' is applied recursively to each
     element of the cell array.

     Numeric arrays are converted to character strings.

     The second argument PROP must be one of

    "alpha"
          True for characters that are alphabetic (letters).

    "alnum"
    "alphanum"
          True for characters that are alphabetic or digits.

    "lower"
          True for lowercase letters.

    "upper"
          True for uppercase letters.

    "digit"
          True for decimal digits (0-9).

    "xdigit"
          True for hexadecimal digits (a-fA-F0-9).

    "space"
    "wspace"
          True for whitespace characters (space, formfeed, newline,
          carriage return, tab, vertical tab).

    "punct"
          True for punctuation characters (printing characters except
          space or letter or digit).

    "cntrl"
          True for control characters.

    "graph"
    "graphic"
          True for printing characters except space.

    "print"
          True for printing characters including space.

    "ascii"
          True for characters that are in the range of ASCII encoding.


     *See also:* *note isalpha: doc-isalpha, *note isalnum:
     doc-isalnum, *note islower: doc-islower, *note isupper:
     doc-isupper, *note isdigit: doc-isdigit, *note isxdigit:
     doc-isxdigit, *note isspace: doc-isspace, *note ispunct:
     doc-ispunct, *note iscntrl: doc-iscntrl, *note isgraph:
     doc-isgraph, *note isprint: doc-isprint, *note isascii:
     doc-isascii.


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.
Multiple input arguments and return values of functions are organized as
another data container, the comma separated list.

* Menu:

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


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

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

* Menu:

* Basic Usage and Examples::
* Structure Arrays::
* Creating Structures::
* Manipulating Structures::
* Processing Data in Structures::


File: octave.info,  Node: Basic Usage and Examples,  Next: Structure Arrays,  Up: Structures

6.1.1 Basic Usage and Examples
------------------------------

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.  The `.' character separates
the structure name from the field name and indicates to Octave that this
variable is a structure.  To print the value of the structure you can
type its name, just as for any other variable:

     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 just like any other variable:

     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.

     x.b.d = 3;
     x.b
          => ans =
             {
               d = 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:

     a.b.c.d.e = 1;
     a
          => a =
             {
               b =
               {
                 c =
                 {
                   1x1 struct array containing the fields:

                   d: 1x1 struct
                 }
               }
             }

This prevents long and confusing output from large deeply nested
structures.  The number of levels to print for nested structures may be
set with the function `struct_levels_to_print', and the function
`print_struct_array_contents' may be used to enable printing of the
contents of structure arrays.

 -- Built-in Function: VAL = struct_levels_to_print ()
 -- Built-in Function: OLD_VAL = struct_levels_to_print (NEW_VAL)
 -- Built-in Function:  struct_levels_to_print (NEW_VAL, "local")
     Query or set the internal variable that specifies the number of
     structure levels to display.

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

 -- Built-in Function: VAL = print_struct_array_contents ()
 -- Built-in Function: OLD_VAL = print_struct_array_contents (NEW_VAL)
 -- Built-in Function:  print_struct_array_contents (NEW_VAL, "local")
     Query or set the internal variable that specifies whether to print
     struct array contents.  If true, values of struct array elements
     are printed.  This variable does not affect scalar structures.
     Their elements are always printed.  In both cases, however,
     printing will be limited to the number of levels specified by
     STRUCT_LEVELS_TO_PRINT.

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

   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.

     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.

     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:

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

                 -0.40455  -0.91451
                 -0.91451   0.40455

               s =

                  0.00000   0.00000   0.00000
                  0.00000   5.46499   0.00000
                  0.00000   0.00000   0.36597

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


File: octave.info,  Node: Structure Arrays,  Next: Creating Structures,  Prev: Basic Usage and Examples,  Up: Structures

6.1.2 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.  Conceptually, a structure
array can also be seen as an array of structures with identical fields.
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.  Another way to
create a structure array is with the `struct' function (*note Creating
Structures::).  As previously, to print the value of the structure
array, you can type its name:

     x
          => x =
             {
               1x2 struct array containing the fields:

                 a
                 b
             }

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

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

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

     x.a
          =>
             ans = string1
             ans = string2

   Here is another example, using this comma separated list on the
left-hand side of an assignment:

     [x.a] = deal("new string1", "new string2");
      x(1).a
          => ans = new string1
      x(2).a
          => ans = new string2

   Just as for numerical arrays, it is possible to use vectors as
indices (*note Index Expressions::):

     x(3:4) = x(1:2);
     [x([1,3]).a] = deal("other string1", "other string2");
     x.a
          =>
             ans = other string1
             ans = new string2
             ans = other string2
             ans = new string2

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

     size(x)
          => ans =

               1   4

   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 =
             {
               1x3 struct array containing the fields:

                 call1
                 call2
             }

     in(1) = [];
     in.call1
          =>
            ans = Inf
            ans = last


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

6.1.3 Creating Structures
-------------------------

Besides the index operator ".", Octave can use dynamic naming "(var)"
or the `struct' function to create structures.  Dynamic naming uses the
string value of a variable as the field name.  For example:

     a = "field2";
     x.a = 1;
     x.(a) = 2;
     x
          => x =
             {
               a =  1
               field2 =  2
             }

   More realistically, all of the functions that operate on strings can
be used to build the correct field name before it is entered into the
data structure.

     names = ["Bill"; "Mary"; "John"];
     ages  = [37; 26; 31];
     for i = 1:rows (names)
       database.(names(i,:)) = ages(i);
     endfor
     database
          => database =
             {
               Bill =  37
               Mary =  26
               John =  31
             }

   The third way to create structures is 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:

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

     s.field2
          =>
             ans =  2
             ans = two

     s.field3
          =>
             ans =  3
             ans =  3

   If you want to create a struct which contains a cell array as an
individual field, you must wrap it in another cell array as shown in
the following example:

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

             {
               [1,1] =  1
               [1,2] = one
             }

               field2 =  2
             }


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

     If the argument is an object, return the underlying struct.

   The function `isstruct' can be used to test if an object is a
structure or a structure array.

 -- Built-in Function:  isstruct (X)
     Return true if X is a structure or a structure array.

     *See also:* *note ismatrix: doc-ismatrix, *note iscell:
     doc-iscell, *note isa: doc-isa.


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

6.1.4 Manipulating Structures
-----------------------------

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

 -- Built-in Function:  nfields (S)
     Return the number of fields of the structure S.

 -- 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 (X, NAME)
     Return true if the X is a structure and it includes an element
     named NAME.  If NAME is a cell array of strings then a logical
     array of equal dimension is returned.

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

          ss(1,2).fd(3).b = 5;
          getfield (ss, {1,2}, "fd", {3}, "b")
             => 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)
             => 5

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

 -- Function File: [K1, ..., V1] = setfield (S, K1, V1, ...)
     Set a field member in a (nested) structure array.  For example:

          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 the same result as in the above example could be
     achieved by:

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

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

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

     *See also:* *note cellstr: doc-cellstr, *note iscellstr:
     doc-iscellstr, *note setfield: doc-setfield.

 -- Function File: [T, P] = orderfields (S1)
 -- Function File: [T, P] = orderfields (S1, S2)
     Return a copy of S1 with fields arranged alphabetically or as
     specified by S2.

     Given one struct, arrange field names in S1 alphabetically.

     If the second argument is a struct, 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 containing the
     fieldnames of S1 in the desired order.

     The optional second output argument P is assigned the permutation
     vector which converts the original name order into the new name
     order.

     Examples:

          s = struct("d", 4, "b", 2, "a", 1, "c", 3);
          t1 = orderfields (s)
               => t1 =
                  {
                    a =  1
                    b =  2
                    c =  3
                    d =  4
                  }
          t = struct("d", {}, "c", {}, "b", "a", {});
          t2 = orderfields (s, t)
               => t2 =
                  {
                    d =  4
                    c =  3
                    b =  2
                    a =  1
                  }
          t3 = orderfields (s, [3, 2, 4, 1]);
               => t3 =
                  {
                    a =  1
                    b =  2
                    c =  3
                    d =  4
                  }
          [t4, p] = orderfields (s, {"d", "c", "b", "a"})
               => t4 =
                  {
                    d =  4
                    c =  3
                    b =  2
                    a =  1
                  }
                  p =
                     1
                     4
                     2
                     3

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

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

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

     *See also:* *note subsref: doc-subsref, *note subsasgn:
     doc-subsasgn.


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

6.1.5 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.  *Note doc-structfun::.

   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)]'.  For example:

            s = struct('name', {'Peter', 'Hannah', 'Robert'},
                       'age', {23, 16, 3});
            c = struct2cell(s)
               => c = {1x1x3 Cell Array}
            c(1,1,:)(:)
               => ans =
                  {
                    [1,1] = Peter
                    [2,1] = Hannah
                    [3,1] = Robert
                  }
            c(2,1,:)(:)
               => ans =
                  {
                    [1,1] = 23
                    [2,1] = 16
                    [3,1] = 3
                  }

     *See also:* *note cell2struct: doc-cell2struct, *note fieldnames:
     doc-fieldnames.


File: octave.info,  Node: Cell Arrays,  Next: Comma Separated Lists,  Prev: 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.

* Menu:

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


File: octave.info,  Node: Basic Usage of Cell Arrays,  Next: Creating Cell Arrays,  Up: Cell Arrays

6.2.1 Basic Usage of Cell Arrays
--------------------------------

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)};

To access the elements of a cell array, it can be indexed with the {
and } operators.  Thus, 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 = a string
          => ans =

                    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
              }

   Details on indexing cell arrays are explained in *note Indexing Cell
Arrays::.

   In general nested cell arrays are displayed hierarchically as in the
previous example.  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.  For example:

          c = {1, 2, {31, 32}};
          celldisp (c, "b")
             =>
                b{1} =
                 1
                b{2} =
                 2
                b{3}{1} =
                 31
                b{3}{2} =
                 32

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

   To test if an object is a cell array, use the `iscell' function.
For example:

     iscell(c)
          => ans = 1

     iscell(3)
          => ans = 0

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

     *See also:* *note ismatrix: doc-ismatrix, *note isstruct:
     doc-isstruct, *note iscellstr: doc-iscellstr, *note isa: doc-isa.


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

6.2.2 Creating Cell Array
-------------------------

The introductory example (*note Basic Usage of Cell Arrays::) 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 is 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 multi-dimensional.
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 are 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 *note `size': doc-size. function also works for
cell arrays.  As do other functions describing the size of an object,
such as *note `length': doc-length, *note `numel': doc-numel, *note
`rows': doc-rows, and *note `columns': doc-columns.

 -- Built-in Function:  cell (N)
 -- Built-in Function:  cell (M, N)
 -- Built-in Function:  cell (M, N, K, ...)
 -- Built-in Function:  cell ([M N ...])
     Create a new cell array object.  If invoked with a single scalar
     integer argument, return a square NxN cell array.  If invoked with
     two or more scalar integer arguments, or a vector of integer
     values, return an array with the given dimensions.

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

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

          num2cell([1,2;3,4])
               => ans =
                  {
                    [1,1] =  1
                    [2,1] =  3
                    [1,2] =  2
                    [2,2] =  4
                  }
          num2cell([1,2;3,4],1)
               => ans =
                  {
                    [1,1] =
                       1
                       3
                    [1,2] =
                       2
                       4
                  }

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

 -- Loadable Function: C = mat2cell (A, M, N)
 -- Loadable Function: C = mat2cell (A, D1, D2, ...)
 -- Loadable Function: C = 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 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:* *note num2cell: doc-num2cell, *note cell2mat:
     doc-cell2mat.

 -- Loadable Function: SL = cellslices (X, LB, UB, DIM)
     Given an array X, this function produces a cell array of slices
     from the array determined by the index vectors LB, UB, for lower
     and upper bounds, respectively.  In other words, it is equivalent
     to the following code:

          n = length (lb);
          sl = cell (1, n);
          for i = 1:length (lb)
            sl{i} = x(:,...,lb(i):ub(i),...,:);
          endfor

     The position of the index is determined by DIM.  If not specified,
     slicing is done along the first non-singleton dimension.

     *See also:* *note cell2mat: doc-cell2mat, *note cellindexmat:
     doc-cellindexmat, *note cellfun: doc-cellfun.


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

6.2.3 Indexing Cell Arrays
--------------------------

As shown in *note Basic Usage of Cell Arrays:: elements can be
extracted from cell arrays using the `{' and `}' operators.  If you
want to extract or access subarrays which are still cell arrays, you
need to use the `(' and `)' operators.  The following example
illustrates the difference:

     c = {"1", "2", "3"; "a", "b", "c"; "4", "5", "6"};
     c{2,3}
          => ans = c

     c(2,3)
          => ans =
             {
               [1,1] = c
             }

So with `{}' you access elements of a cell array, while with `()' you
access a sub array of a cell array.

   Using the `(' and `)' operators, indexing works for cell arrays like
for multi-dimensional 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
command:

     c(:, [1, 3]) = {0}
          =>  =
             {
               [1,1] = 0
               [2,1] = 0
               [3,1] = 0
               [1,2] = 2
               [2,2] =  10
               [3,2] =  20
               [1,3] = 0
               [2,3] = 0
               [3,3] = 0
             }

   Note, that the above can also be achieved like this:

     c(:, [1, 3]) = 0;

Here, the scalar `0' is automatically promoted to cell array `{0}' and
then assigned to the subarray of `c'.

   To give another example for indexing cell arrays with `()', you can
exchange the first and the second row of a cell array as in the
following command:

     c = {1, 2, 3; 4, 5, 6};
     c([1, 2], :) = c([2, 1], :)
          => =
             {
               [1,1] =  4
               [2,1] =  1
               [1,2] =  5
               [2,2] =  2
               [1,3] =  6
               [2,3] =  3
             }

   Accessing multiple elements of a cell array with the `{' and `}'
operators will result in a comma-separated list of all the requested
elements (*note Comma Separated Lists::).  Using the `{' and `}'
operators the first two rows in the above example can be swapped back
like this:

     [c{[1,2], :}] = deal(c{[2, 1], :})
          => =
             {
               [1,1] =  1
               [2,1] =  4
               [1,2] =  2
               [2,2] =  5
               [1,3] =  3
               [2,3] =  6
             }

   As for struct arrays and numerical arrays, the empty matrix `[]' can
be used to delete elements from a cell array:

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

   The following example shows how to just remove the contents of cell
array elements but not delete the space for them:

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

   The indexing operations operate on the cell array and not on the
objects within the cell array.  By contrast, `cellindexmat' applies
matrix indexing to the objects within each cell array entry and returns
the requested values.

 -- Loadable Function: Y = cellindexmat (X, VARARGIN)
     Given a cell array of matrices X, this function computes

            Y = cell (size (X));
            for i = 1:numel (X)
              Y{i} = X{i}(varargin{:});
            endfor

     *See also:* *note cellslices: doc-cellslices, *note cellfun:
     doc-cellfun.


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

6.2.4 Cell Arrays of Strings
----------------------------

One common use of cell arrays is to store multiple strings in the same
variable.  It is also 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.  For cases,
where the character matrix representation is required for an operation,
there are several functions that convert a cell array of strings to a
character array and back.  `char' and `strvcat' convert cell arrays to
a character array (*note Concatenating Strings::), while the function
`cellstr' converts a character array to a cell array of strings:

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

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

   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 to the string
argument:

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

The following string functions support cell arrays of strings: `char',
`strvcat', `strcat' (*note Concatenating Strings::), `strcmp',
`strncmp', `strcmpi', `strncmpi' (*note Comparing Strings::),
`str2double', `deblank', `strtrim', `strtrunc', `strfind', `strmatch',
, `regexp', `regexpi' (*note Manipulating Strings::) and `str2double'
(*note String Conversions::).

   The function `iscellstr' can be used to test if an object is a cell
array of strings.

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

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


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

6.2.5 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 simplest way to process that data is
to iterate through it using one or more `for' loops.  The same idea can
be implemented more easily through the use of the `cellfun' function
that calls a user-specified function on all elements of a cell array.
*Note doc-cellfun::.

   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 matrices, or cell arrays, and `cat' must
     be able to concatenate them together.

     *See also:* *note mat2cell: doc-mat2cell, *note num2cell:
     doc-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)'.  If DIM is omitted, a value
     of 1 is assumed.

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


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

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

Comma separated lists (1) are the basic argument type to all Octave
functions - both for input and return arguments.  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 assignment.  For example

     x = [1 0 1 0 0 1 1; 0 0 0 0 0 0 7];
     [I, J] = find (X, 2, "last");

Here, `X, 2, "last"' is a comma separated list constituting the input
arguments of `find'.  `find' returns a comma separated list of output
arguments which is assigned element by element to the comma separated
list `I, J'.

   Another example of where comma separated lists are used is in the
creation of a new array with `[]' (*note Matrices::) or the creation of
a cell array with `{}' (*note Basic Usage of Cell Arrays::).  In the
expressions

     a = [1, 2, 3, 4];
     c = {4, 5, 6, 7};

both `1, 2, 3, 4' and `4, 5, 6, 7' are comma separated lists.

   Comma separated lists cannot be directly manipulated by the user.
However, both structure arrays and cell arrays can be converted into
comma separated lists, and thus used in place of explicitly written
comma separated lists.  This feature is useful in many ways, as will be
shown in the following subsections.

* Menu:

* Comma Separated Lists Generated from Cell Arrays::
* Comma Separated Lists Generated from Structure Arrays::

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

   (1) Comma-separated lists are also sometimes informally referred to
as "cs-lists".


File: octave.info,  Node: Comma Separated Lists Generated from Cell Arrays,  Next: Comma Separated Lists Generated from Structure Arrays,  Up: Comma Separated Lists

6.3.1 Comma Separated Lists Generated from Cell Arrays
------------------------------------------------------

As has been mentioned above (*note Indexing Cell Arrays::), elements of
a cell array can be extracted into a comma separated list with the `{'
and `}' operators.  By surrounding this list with `[' and `]', it can
be concatenated into an array.  For example:

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

   Similarly, it is possible to create a new cell array containing cell
elements selected with `{}'.  By surrounding the list with `{' and `}'
a new cell array will be created, as the following example illustrates:

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

   Furthermore, cell elements (accessed by `{}') can be passed 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 individual arguments.  The two calls to `printf' in the
following example are identical but the latter is simpler and can
handle cell arrays of an arbitrary size:

     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

   If used on the left-hand side of an assignment, a comma separated
list generated with `{}' can be assigned to.  An example is

     in{1} = [10, 20, 30, 40, 50, 60, 70, 80, 90];
     in{2} = inf;
     in{3} = "last";
     in{4} = "first";
     out = cell (4, 1);
     [out{1:3}] = find (in{1 : 3});
     [out{4:6}] = find (in{[1, 2, 4]})
          => out =
             {
               [1,1] = 1
               [2,1] = 9
               [3,1] = 90
               [4,1] = 1
               [3,1] = 1
               [4,1] = 10
             }


File: octave.info,  Node: Comma Separated Lists Generated from Structure Arrays,  Prev: Comma Separated Lists Generated from Cell Arrays,  Up: Comma Separated Lists

6.3.2 Comma Separated Lists Generated from Structure Arrays
-----------------------------------------------------------

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

     x = ceil (randn (10, 1));
     in = struct ("call1", {x, 3, "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.

   There is one built-in variable with a special meaning.  The `ans'
variable always contains the result of the last computation, where the
output wasn't assigned to any variable.  The code `a = cos (pi)' will
assign the value -1 to the variable `a', but will not change the value
of `ans'.  However, the code `cos (pi)' will set the value of `ans' to
-1.

   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.

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

          3^2 + 4^2

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

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

     *See also:* *note iskeyword: doc-iskeyword, *note exist:
     doc-exist, *note who: doc-who.

 -- Function File: VARNAME = genvarname (STR)
 -- Function File: VARNAME = genvarname (STR, EXCLUSIONS)
     Create unique variable(s) from STR.  If EXCLUSIONS is given, then
     the variable(s) will be unique to each other and to EXCLUSIONS
     (EXCLUSIONS may be either a string or a cellstr).

     If STR is a cellstr, then a unique variable is created for each
     cell in STR.

          x = 3.141;
          genvarname ("x", who ())
            => x1

     If WANTED is a cell array, genvarname will make sure the returned
     strings are distinct:

          genvarname ({"foo", "foo"})
            =>
               {
                 [1,1] = foo
                 [1,2] = foo1
               }

     Note that the result is a char array/cell array of strings, not the
     variables themselves.  To define a variable, `eval()' can be used.
     The following trivial example sets `x' to `42'.

          name = genvarname ("x");
          eval ([name " = 42"]);
            => x =  42

     Also, this can be useful for creating unique struct field names.

          x = struct ();
          for i = 1:3
            x.(genvarname ("a", fieldnames (x))) = i;
          endfor
            => x =
               {
                 a =  1
                 a1 =  2
                 a2 =  3
               }

     Since variable names may only contain letters, digits and
     underscores, genvarname replaces any sequence of disallowed
     characters with an underscore.  Also, variables may not begin with
     a digit; in this case an underscore is added before the variable
     name.

     Variable names beginning and ending with two underscores "__" are
     valid but they are used internally by octave and should generally
     be avoided, therefore genvarname will not generate such names.

     genvarname will also make sure that returned names do not clash
     with keywords such as "for" and "if".  A number will be appended
     if necessary.  Note, however, that this does *not* include
     function names, such as "sin".  Such names should be included in
     AVOID if necessary.

     *See also:* *note isvarname: doc-isvarname, *note exist:
     doc-exist, *note tmpnam: doc-tmpnam, *note eval: doc-eval.

 -- Function File:  namelengthmax ()
     Return the MATLAB compatible maximum variable name length.  Octave
     is capable of storing strings up to 2^31 - 1 in length.  However
     for MATLAB compatibility all variable, function, and structure
     field names should be shorter than the length supplied by
     `namelengthmax'.  In particular variables stored to a MATLAB file
     format will have their names truncated to this length.

* Menu:

* Global Variables::
* Persistent Variables::
* Status of Variables::


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 true if NAME is a globally visible variable.  For example:

          global x
          isglobal ("x")
               => 1

     *See also:* *note isvarname: doc-isvarname, *note exist: doc-exist.


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 disk, we get the following behavior.

     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,  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
 -- Command:  who pattern ...
 -- Command:  who option pattern ...
 -- Command: C = who ("pattern", ...)
     List currently defined variables matching the given patterns.
     Valid pattern syntax is the same as described for the `clear'
     command.  If no patterns are supplied, all variables are listed.
     By default, only variables visible in the local scope are
     displayed.

     The following are valid options but may not be combined.

    `global'
          List variables in the global scope rather than the current
          scope.

    `-regexp'
          The patterns are considered to be regular expressions when
          matching the variables to display.  The same pattern syntax
          accepted by the `regexp' function is used.

    `-file'
          The next argument is treated as a filename.  All variables
          found within the specified file are listed.  No patterns are
          accepted when reading variables from a file.

     If called as a function, return a cell array of defined variable
     names matching the given patterns.

     *See also:* *note whos: doc-whos, *note isglobal: doc-isglobal,
     *note isvarname: doc-isvarname, *note exist: doc-exist, *note
     regexp: doc-regexp.

 -- Command:  whos
 -- Command:  whos pattern ...
 -- Command:  whos option pattern ...
 -- Command: S = whos ("pattern", ...)
     Provide detailed information on currently defined variables
     matching the given patterns.  Options and pattern syntax are the
     same as for the `who' command.  Extended information about each
     variable is summarized in a table with the following default
     entries.

    Attr
          Attributes of the listed variable.  Possible attributes are:
         blank
               Variable in local scope

         `a'
               Automatic variable.  An automatic variable is one
               created by the interpreter, for example `argn'.

         `c'
               Variable of complex type.

         `f'
               Formal parameter (function argument).

         `g'
               Variable with global scope.

         `p'
               Persistent variable.

    Name
          The name of the variable.

    Size
          The logical size of the variable.  A scalar is 1x1, a vector
          is 1xN or Nx1, a 2-D matrix is MxN.

    Bytes
          The amount of memory currently used to store the variable.

    Class
          The class of the variable.  Examples include double, single,
          char, uint16, cell, and struct.

     The table can be customized to display more or less information
     through the function `whos_line_format'.

     If `whos' is called as a function, return a struct array of defined
     variable names matching the given patterns.  Fields in the
     structure describing each variable are: name, size, bytes, class,
     global, sparse, complex, nesting, persistent.

     *See also:* *note who: doc-who, *note whos_line_format:
     doc-whos_line_format.

 -- Built-in Function: VAL = whos_line_format ()
 -- Built-in Function: OLD_VAL = whos_line_format (NEW_VAL)
 -- Built-in Function:  whos_line_format (NEW_VAL, "local")
     Query or set the format string used by the command `whos'.

     A full format string is:

          %[modifier]<command>[:width[:left-min[:balance]]];

     The following command sequences are available:

    `%a'
          Prints attributes of variables (g=global, p=persistent,
          f=formal parameter, a=automatic variable).

    `%b'
          Prints number of bytes occupied by variables.

    `%c'
          Prints class names of variables.

    `%e'
          Prints elements held by variables.

    `%n'
          Prints variable names.

    `%s'
          Prints dimensions of variables.

    `%t'
          Prints type names of variables.

     Every command may also have an alignment modifier:

    `l'
          Left alignment.

    `r'
          Right alignment (default).

    `c'
          Column-aligned (only applicable to command %s).

     The `width' parameter is a positive integer specifying the minimum
     number of columns used for printing.  No maximum is needed as the
     field will auto-expand as required.

     The parameters `left-min' and `balance' are only available when the
     column-aligned modifier is used with the command `%s'.  `balance'
     specifies the column number within the field width which will be
     aligned between entries.  Numbering starts from 0 which indicates
     the leftmost column.  `left-min' specifies the minimum field width
     to the left of the specified balance column.

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

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

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

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

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

   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 lowercase and uppercase 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.

    `-classes, -c'
          Clears the class structure table and clears all objects.

    `-regexp, -r'
          The arguments are treated as regular expressions as any
          variables that match will be cleared.
     With the exception of `exclusive', all long options can be used
     without the dash as well.

 -- Function File:  pack ()
     Consolidate workspace memory in MATLAB.  This function is provided
     for compatibility, but does nothing in Octave.

   Information about a function or variable such as its 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.

 -- Command:  type NAME ...
 -- Command:  type -q NAME ...
 -- Function File: dfns = type ("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 behavior.

     If an output argument is requested nothing is displayed.  Instead,
     a cell array of strings is returned, where each element
     corresponds to the definition of each requested function.

 -- 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:* *note help: doc-help, *note lookfor: doc-lookfor.

 -- Command:  what
 -- Command:  what DIR
 -- Function File: w = what (DIR)
     List the Octave specific files in directory DIR.  If DIR is not
     specified then the current directory is used.  If a return
     argument is requested, the files found are returned in the
     structure W.

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


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 (2-D)
and higher multi-dimensional arrays are indexed using either one index
or N indices where N is the dimension of the array.  When using a
single index expression to index 2-D or higher data the elements of the
array are taken in column-first order (like Fortran).

   The output from indexing assumes the dimensions of the index
expression.  For example:

     a(2)       # result is a scalar
     a(1:2)     # result is a row vector
     a([1; 2])  # result is 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(:)       # result is a column vector
     a(:)'      # result is a row vector

   The above two code idioms are often used in place of `reshape' when
a simple vector, rather than an arbitrarily sized array, is needed.

   Given the matrix

     a = [1, 2; 3, 4]

all of the following expressions are equivalent and select the first
row of the matrix.

     a(1, [1, 2])  # row 1, columns 1 and 2
     a(1, 1:2)     # row 1, columns in range 1-2
     a(1, :)       # row 1, all columns

   In index expressions the keyword `end' automatically refers to the
last entry for a particular dimension.  This magic index can also be
used in ranges and typically eliminates the needs to call `size' or
`length' to gather array bounds before indexing.  For example:

     a = [1, 2, 3, 4];

     a(1:end/2)        # first half of a => [1, 2]
     a(end + 1) = 5;   # append element
     a(end) = [];      # delete element
     a(1:2:end)        # odd elements of a => [1, 3]
     a(2:2:end)        # even elements of a => [2, 4]
     a(end:-1:1)       # reversal of a => [4, 3, 2 , 1]

* Menu:

* Advanced Indexing::


File: octave.info,  Node: Advanced Indexing,  Up: Index Expressions

8.1.1 Advanced Indexing
-----------------------

An array with `n' dimensions can be indexed using `m' indices.  More
generally, the set of index tuples determining the result is formed by
the Cartesian product of the index vectors (or ranges or scalars).

   For the ordinary and most common case, `m == n', and each index
corresponds to its respective dimension.  If `m < n' and every index is
less than the size of the array in the i^th dimension, `m(i) < n(i)',
then the index expression is padded with trailing singleton dimensions
(`[ones (m-n, 1)]').  If `m < n' but one of the indices `m(i)' is
outside the size of the current array, then the last `n-m+1' dimensions
are folded into a single dimension with an extent equal to the product
of extents of the original dimensions.  This is easiest to understand
with an example.

     a = reshape (1:8, 2, 2, 2)  # Create 3-D array
     a =

     ans(:,:,1) =

        1   3
        2   4

     ans(:,:,2) =

        5   7
        6   8

     a(2,1,2);   # Case (m == n): ans = 6
     a(2,1);     # Case (m < n), idx within array:
                 # equivalent to a(2,1,1), ans = 2
     a(2,4);     # Case (m < n), idx outside array:
                 # Dimension 2 & 3 folded into new dimension of size 2x2 = 4
                 # Select 2nd row, 4th element of [2, 4, 6, 8], ans = 8

   One advanced use of indexing is to create arrays filled with a single
value.  This can be done by using an index of ones on a scalar value.
The result is an object with the dimensions of the index expression and
every element equal to the original scalar.  For example, the following
statements

     a = 13;
     a(ones (1, 4))

produce a vector whose four elements are all equal to 13.

   Similarly, by indexing a scalar with two vectors of ones it is
possible to create a matrix.  The following statements

     a = 13;
     a(ones (1, 2), ones (1, 3))

create a 2x3 matrix with all elements equal to 13.

   The last example could also be written as

     13(ones (2, 3))

   It is more efficient to use indexing rather than the code
construction `scalar * ones (N, M, ...)' because it avoids the
unnecessary multiplication operation.  Moreover, multiplication may not
be defined for the object to be replicated whereas indexing an array is
always defined.  The following code shows how to create a 2x3 cell
array from a base unit which is not itself a scalar.

     {"Hello"}(ones (2, 3))

   It should be, noted that `ones (1, n)' (a row vector of ones)
results in a range (with zero increment).  A range is stored internally
as a starting value, increment, end value, and total number of values;
hence, it is more efficient for storage than a vector or matrix of ones
whenever the number of elements is greater than 4.  In particular, when
`r' is a row vector, the expressions

       r(ones (1, n), :)

       r(ones (n, 1), :)

will produce identical results, but the first one will be significantly
faster, at least for `r' and `n' large enough.  In the first case the
index is held in compressed form as a range which allows Octave to
choose a more efficient algorithm to handle the expression.

   A general recommendation, for a user unaware of these subtleties, is
to use the function `repmat' for replicating smaller arrays into bigger
ones.

   A second use of indexing is to speed up code.  Indexing is a fast
operation and judicious use of it can reduce the requirement for
looping over individual array elements which is a slow operation.

   Consider the following example which creates a 10-element row vector
a containing the values a(i) = sqrt(i).

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

It is quite inefficient to create a vector using a loop like this.  In
this case, it would have been much more efficient to use the expression

     a = sqrt (1:10);

which avoids the loop entirely.

   In cases where a loop cannot be avoided, or a number of values must
be combined to form a larger matrix, it is generally faster to set the
size of the matrix first (pre-allocate storage), 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

because Octave does not have to repeatedly resize the intermediate
result.

 -- Function File: IND = sub2ind (DIMS, I, J)
 -- Function File: IND = sub2ind (DIMS, S1, S2, ..., SN)
     Convert subscripts to 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.  The matrix is
     linearly indexed moving from one column to next, filling up all
     rows in each column.

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

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

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

     The following example shows how to convert the linear index `8' in
     a 3-by-3 matrix into a subscript.  The matrix is linearly indexed
     moving from one column to next, filling up all rows in each column.

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

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

 -- Built-in Function:  isindex (IND)
 -- Built-in Function:  isindex (IND, N)
     Return true if IND is a valid index.  Valid indices are either
     positive integers (although possibly of real data type), or logical
     arrays.  If present, N specifies the maximum extent of the
     dimension to be indexed.  When possible the internal result is
     cached so that subsequent indexing using IND will not perform the
     check again.

 -- Built-in Function: VAL = allow_noninteger_range_as_index ()
 -- Built-in Function: OLD_VAL = allow_noninteger_range_as_index
          (NEW_VAL)
 -- Built-in Function:  allow_noninteger_range_as_index (NEW_VAL,
          "local")
     Query or set the internal variable that controls whether
     non-integer ranges are allowed as indices.  This might be useful
     for MATLAB compatibility; however, it is still not entirely
     compatible because MATLAB treats the range expression differently
     in different contexts.

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.


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 a 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)
 -- Built-in Function:  max_recursion_depth (NEW_VAL, "local")
     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.

     When called from inside a function with the "local" option, the
     variable is changed locally for the function and any subroutines
     it calls.  The original variable value is restored when exiting
     the function.

   ---------- 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.  The element-by-element operators and functions broadcast
(*note Broadcasting::).

X + Y
     Addition.  If both operands are matrices, the number of rows and
     columns must both agree, or they must be broadcastable to the same
     shape.

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, or they must be broadcastable to the
     same shape.

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, or they must be broadcastable to the same
     shape.

X .* Y
     Element-by-element multiplication.  If both operands are matrices,
     the number of rows and columns must both agree, or they must be
     broadcastable to the same shape.

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, or they must be
     broadcastable to the same shape.  If several complex results are
     possible, the one with smallest non-negative argument (angle) is
     taken.  This rule may return a complex root even when a real root
     is also possible.  Use `realpow', `realsqrt', `cbrt', or `nthroot'
     if a real result is preferred.

-X
     Negation.

+X
     Unary plus.  This operator has no effect on the operand.

X'
     Complex conjugate transpose.  For real arguments, this operator is
     the same as the transpose operator.  For complex arguments, this
     operator is equivalent to the expression

          conj (x.')

X.'
     Transpose.

   Note that because Octave's element-by-element operators begin with a
`.', there is a possible ambiguity for statements like

     1./m

because the period could be interpreted either as part of the constant
or as part of the operator.  To resolve this conflict, Octave treats the
expression as if you had typed

     (1) ./ m

and not

     (1.) / m

Although this is inconsistent with the normal behavior of Octave's
lexer, which usually prefers to break the input into tokens by
preferring the longest possible match at any given point, it is more
useful in this case.

 -- Built-in Function:  ctranspose (X)
     Return the complex conjugate transpose of X.  This function and x'
     are equivalent.

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

 -- Built-in Function:  ldivide (X, Y)
     Return the element-by-element left division of X and Y.  This
     function and x . y are equivalent.

     *See also:* *note rdivide: doc-rdivide, *note mldivide:
     doc-mldivide.

 -- Built-in Function:  minus (X, Y)
     This function and x - y are equivalent.

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

 -- Built-in Function:  mldivide (X, Y)
     Return the matrix left division of X and Y.  This function and
     x  y are equivalent.

     *See also:* *note mrdivide: doc-mrdivide, *note ldivide:
     doc-ldivide.

 -- Built-in Function:  mpower (X, Y)
     Return the matrix power operation of X raised to the Y power.
     This function and x ^ y are equivalent.

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

 -- Built-in Function:  mrdivide (X, Y)
     Return the matrix right division of X and Y.  This function and
     x / y are equivalent.

     *See also:* *note mldivide: doc-mldivide, *note rdivide:
     doc-rdivide.

 -- Built-in Function:  mtimes (X, Y)
 -- Built-in Function:  mtimes (X1, X2, ...)
     Return the matrix multiplication product of inputs.  This function
     and x * y are equivalent.  If more arguments are given, the
     multiplication is applied cumulatively from left to right:

            (...((x1 * x2) * x3) * ...)

     At least one argument is required.

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

 -- Built-in Function:  plus (X, Y)
 -- Built-in Function:  plus (X1, X2, ...)
     This function and x + y are equivalent.  If more arguments are
     given, the summation is applied cumulatively from left to right:

            (...((x1 + x2) + x3) + ...)

     At least one argument is required.

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

 -- Built-in Function:  power (X, Y)
     Return the element-by-element operation of X raised to the Y
     power.  If several complex results are possible, returns the one
     with smallest non-negative argument (angle).  Use `realpow',
     `realsqrt', `cbrt', or `nthroot' if a real result is preferred.

     This function and x .^ y are equivalent.

     *See also:* *note mpower: doc-mpower, *note realpow: doc-realpow,
     *note realsqrt: doc-realsqrt, *note cbrt: doc-cbrt, *note nthroot:
     doc-nthroot.

 -- Built-in Function:  rdivide (X, Y)
     Return the element-by-element right division of X and Y.  This
     function and x ./ y are equivalent.

     *See also:* *note ldivide: doc-ldivide, *note mrdivide:
     doc-mrdivide.

 -- Built-in Function:  times (X, Y)
 -- Built-in Function:  times (X1, X2, ...)
     Return the element-by-element multiplication product of inputs.
     This function and x .* y are equivalent.  If more arguments are
     given, the multiplication is applied cumulatively from left to
     right:

            (...((x1 .* x2) .* x3) .* ...)

     At least one argument is required.

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

 -- Built-in Function:  transpose (X)
     Return the transpose of X.  This function and x.' are equivalent.

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

 -- Built-in Function:  uminus (X)
     This function and - x are equivalent.

 -- Built-in Function:  uplus (X)
     This function and + x are equivalent.

