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

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

END-INFO-DIR-ENTRY

   Copyright (C) 1996-2013 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.8.1.

* 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::
* Java Interface:: 
* Packages:: 
* External Code Interface::
* 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::
* Citing Octave in Publications::
* 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::

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

* Introduction to Function and Script Files::
* 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 Anonymous Functions Inline Functions::
* Commands::
* Organization of Functions::

Function Files

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

Function Handles Anonymous Functions Inline 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::
* Manipulation of Plot Windows::
* Use of the 'interpreter' Property::
* 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
* JIT Compiler::               Just-In-Time Compiler for loops
* Miscellaneous Techniques::   Other techniques for speeding up code
* Examples::

Nonlinear Equations

* Solvers::
* Minimizers::

Diagonal and Permutation Matrices

* Basic Usage::          Creation and Manipulation of Diagonal/Permutation Matrices
* Matrix Algebra::       Linear Algebra with Diagonal/Permutation Matrices
* Function Support::     Functions That Are Aware of These Matrices
* Example Code::         Examples of Usage
* Zeros Treatment::      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::
* Base64 and Binary Data Transmission::

Java Interface

* Java Interface Functions::
* Dialog Box Functions::
* FAQ - Frequently asked Questions::

FAQ - Frequently asked Questions

* How to distinguish between Octave and Matlab?::
* How to make Java classes available?::
* How to create an instance of a Java class?::
* How can I handle memory limitations?::
* Which TeX symbols are implemented in dialog functions?::

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

External Code Interface

* 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 Class 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 Dependencies 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::
* Citing Octave in Publications::
* How You Can Contribute to Octave::
* Distribution::


File: octave.info,  Node: Acknowledgements,  Next: Citing Octave in Publications,  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               Adam H. Aitkenhead
Giles Anderson           Joel Andersson           Muthiah Annamalai
Markus Appel             Marco Atzeri             Shai Ayal
Roger Banks              Ben Barrowes             Alexander Barth
David Bateman            Heinz Bauschke           Julien Bect
Roman Belov              Karl Berry               David Billinghurst
Don Bindner              Jakub Bogusz             Moritz Borgmann
Paul Boven               Richard Bovey            John Bradshaw
Marcus Brinkmann         Max Brister              Remy Bruno
Clemens Buchacher        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            Catalin Codreanu
J. D. Cole               Martin Costabel          Michael Creel
Richard Crozier          Jeff Cunningham          Martin Dalecki
Jacob Dawid              Jorge Barros de Abreu    Carlo de Falco
Thomas D. Dean           Philippe Defert          Bill Denney
Fabian Deutsch           Christos Dimitrakakis    Pantxo Diribarne
Vivek Dogra              John Donoghue            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        Brad Froehle
                         Frias
Castor Fu                Eduardo Gallestey        Walter Gautschi
Klaus Gebhardt           Driss Ghaddab            Nicolo Giorgetti
Arun Giridhar            Michael D. Godfrey       Michael Goffioul
Glenn Golden             Tomislav Goles           Keith Goodman
Brian Gough              Steffen Groot            Etienne Grossmann
David Grundberg          Kyle Guinn               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              Martin Hepperle
Jordi Gutiérrez         Yozo Hida                Ryan Hinton
Hermoso
Roman Hodek              A. Scottedward Hodel     Richard Allan Holcombe
Tom Holroyd              David Hoover             Kurt Hornik
Christopher Hulbert      Cyril Humbert            John Hunt
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
Erik Kjellson            Arno J. Klaassen         Alexander Klein
Geoffrey Knauth          Heine Kolltveit          Ken Kouno
Kacper Kowalik           Daniel Kraft             Nir Krakauer
Aravindh                 Oyvind Kristiansen       Artem Krosheninnikov
Krishnamoorthy
Piotr Krzyzanowski       Volker Kuhlmann          Tetsuro Kurita
Philipp Kutin            Miroslaw Kwasniak        Rafael Laboissiere
Kai Labusch              Claude Lacoursiere       Walter Landry
Bill Lash                Dirk Laurie              Maurice LeBrun
Friedrich Leisch         Thorsten Liebig          Jyh-miin Lin
Timo Lindfors            Benjamin Lindner         Ross Lippert
David Livings            Sebastien Loisel         Erik de Castro Lopo
Massimo Lorenzin         Emil Lucretiu            Hoxide Ma
Colin Macdonald          James Macnicol           Jens-Uwe Mager
Rob Mahurin              Alexander Mamonov        Ricardo Marranita
Orestes Mas              Axel Mathéi             Makoto Matsumoto
Tatsuro Matsuoka         Christoph Mayer          Laurent Mazet
G. D. McBain             Ronald van der Meer      Júlio Hoffimann
                                                  Mendes
Ed Meyer                 Thorsten Meyer           Petr Mikulik
Mike Miller              Stefan Monnier           Antoine Moreau
Kai P. Mueller           Hannes Müller           Victor Munoz
Iain Murray              Carmen Navarrete         Todd Neal
Philip Nienhuis          Al Niessner              Felipe G. Nievinski
Rick Niles               Takuji Nishimura         Kai Noda
Patrick Noffke           Eric Norum               Krzesimir Nowak
Michael O'Brien          Peter O'Gorman           Thorsten Ohl
Arno Onken               Valentin                 Luis F. Ortiz
                         Ortega-Clavero
Carl Osterwisch          Janne Olavi              Scott Pakin
                         Paanajärvi
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     Jens Restemeier
Anthony Richardson       Jason Riedy              E. Joshua Rigler
Sander van Rijn          Petter Risholm           Matthew W. Roberts
Peter Rosin              Andrew Ross              Fabio Rossi
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             Falk Tannhäuser         Duncan Temple Lang
Matthew Tenny            Kris Thielemans          Georg Thimm
Corey Thomasson          Olaf Till                Christophe Tournery
Thomas Treichl           Karsten Trulsen          David Turner
Frederick Umminger       Utkarsh Upadhyay         Stefan van der Walt
Peter Van Wieren         James R. Van Zandt       Risto Vanhanen
Gregory Vanuxem          Mihas Varantsou          Ivana Varekova
Sébastien Villemot      Daniel Wagenaar          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: Citing Octave in Publications,  Next: How You Can Contribute to Octave,  Prev: Acknowledgements,  Up: Preface

Citing Octave in Publications
=============================

In view of the many contributions made by numerous developers over many
years it is common courtesy to cite Octave in publications when it has
been used during the course of research or the preparation of figures.
The 'citation' function can automatically generate a recommended
citation text for Octave or any of its packages.  See the help text
below on how to use 'citation'.

 -- Command: citation
 -- Command: citation PACKAGE
     Display instructions for citing GNU Octave or its packages in
     publications.

     When called without an argument, display information on how to cite
     the core GNU Octave system.  When given a package name PACKAGE,
     display information on citing the specific named package.  Note
     that some packages may not yet have instructions on how to cite
     them.

     The GNU Octave developers and its active community of package
     authors have invested a lot of time and effort in creating GNU
     Octave as it is today.  Please give credit where credit is due and
     cite GNU Octave and its packages when you use them.


File: octave.info,  Node: How You Can Contribute to Octave,  Next: Distribution,  Prev: Citing Octave in Publications,  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 is typically used for such problems as solving linear
and nonlinear equations, numerical linear algebra, statistical analysis,
and for performing other numerical experiments.  It may also be used as
a batch-oriented language for automated data processing.

   Until recently GNU Octave provided a command-line interface with
graphical results displayed in separate windows.  The current version
(version 3.8, released in late 2013) also provides, by default, a
graphical user interface.

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

* 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'.
This, by default, starts the graphical user interface (GUI). The central
window in the GUI is the Octave command-line interface.  Octave displays
an initial message and then a prompt indicating it is ready to accept
input.  If you have chosen the traditional command-line interface only
the command prompt appears.  In any case, you can immediately begin
typing Octave commands.

   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, *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, *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: Invalid input argument


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

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

Functions and commands 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, command, 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::


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 External Code Interface::.

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


File: octave.info,  Node: A Sample Command 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: 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.

'--built-in-docstrings-file FILENAME'
     Specify the name of the file containing documentation strings for
     the built-in functions of Octave.  This value is normally correct
     and should only need to specified in extraordinary situations.

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

'--debug-jit'
     Enable JIT compiler debugging and tracing.

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

'--force-gui'
     Force the graphical user interface (GUI) to start.

'--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, *note Emacs Octave
     Support::.

'--jit-compiler'
     Enable the JIT compiler used for accelerating loops.

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

'--no-gui'
     Disable the graphical user interface (GUI) and use the command line
     interface (CLI) instead.

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

'--no-window-system'
'-W'
     Disable use of a windowing system including graphics.  This forces
     a strictly terminal-only environment.

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

'--texi-macros-file FILENAME'
     Specify the name of the file containing Texinfo macros for use by
     makeinfo.

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

     Note that this does not enable the 'Octave:matlab-incompatible'
     warning, which you might want if you want to be told about writing
     code that works in Octave but not MATLAB (*note warning:
     XREFwarning, *note warning_ids: XREFwarning_ids.).

'--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:
     XREFprogram_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: XREFprogram_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'
 -- Command: help '.'
     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.

     Given the single argument '.', list all operators 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: XREFdoc, *note lookfor: XREFlookfor, *note
     which: XREFwhich.

 -- Command: doc FUNCTION_NAME
     Display documentation for the function FUNCTION_NAME directly from
     an online 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 online 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: XREFhelp.

 -- 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: XREFhelp, *note doc: XREFdoc, *note which:
     XREFwhich.

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

 -- Command: news
 -- Command: news PACKAGE
     Display the current NEWS file for Octave or an installed package.

     When called without an argument, display the NEWS file for Octave.
     When given a package name 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 FNAME'.

     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: XREFinfo_program, *note doc: XREFdoc,
     *note help: XREFhelp, *note makeinfo_program: XREFmakeinfo_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: XREFinfo_file, *note doc: XREFdoc, *note
     help: XREFhelp, *note makeinfo_program: XREFmakeinfo_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 texi_macros_file: XREFtexi_macros_file, *note
     info_file: XREFinfo_file, *note info_program: XREFinfo_program,
     *note doc: XREFdoc, *note help: XREFhelp.

 -- Built-in Function: VAL = texi_macros_file ()
 -- Built-in Function: OLD_VAL = texi_macros_file (NEW_VAL)
 -- Built-in Function: texi_macros_file (NEW_VAL, "local")
     Query or set the internal variable that specifies the name of the
     file containing Texinfo macros that are prepended to documentation
     strings before they are passed to makeinfo.  The default value is
     'OCTAVE-HOME/share/octave/VERSION/etc/macros.texi', 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_TEXI_MACROS_FILE',
     or the command line argument '--texi-macros-file FNAME'.

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

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

     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 doc_cache_create: XREFdoc_cache_create, *note
     lookfor: XREFlookfor, *note info_program: XREFinfo_program, *note
     doc: XREFdoc, *note help: XREFhelp, *note makeinfo_program:
     XREFmakeinfo_program.

 -- Built-in Function: VAL = built_in_docstrings_file ()
 -- Built-in Function: OLD_VAL = built_in_docstrings_file (NEW_VAL)
 -- Built-in Function: built_in_docstrings_file (NEW_VAL, "local")
     Query or set the internal variable that specifies the name of the
     file containing docstrings for built-in Octave functions.  The
     default value is
     'OCTAVE-HOME/share/octave/VERSION/etc/built-in-docstrings', 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_BUILT_IN_DOCSTRINGS_FILE', or the command line argument
     '--built-in-docstrings-file FNAME'.

     Note: This variable is only used when Octave is initializing
     itself.  Modifying it during a running session of Octave will have
     no effect.

 -- 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: doc_cache_create (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
     built-in operators, etc.  is generated.

     See also: *note doc_cache_file: XREFdoc_cache_file, *note lookfor:
     XREFlookfor, *note path: XREFpath.

 -- Built-in 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".

 -- Built-in 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
 -- Command: history OPT1 ...
 -- Built-in Function: H = history ()
 -- Built-in Function: H = history (OPT1, ...)
     If invoked with no arguments, 'history' displays a list of commands
     that you have executed.  Valid options are:

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

     '-c'
          Clear the history list.

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

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

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

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

     If invoked with a single output argument, the history will be saved
     to that argument as a cell string and will not be output to screen.

 -- Command: edit_history
 -- Command: edit_history CMD_NUMBER
 -- Command: edit_history FIRST LAST
     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.  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 leaving the editor.

     When invoked with no arguments, edit the previously executed
     command; With one argument, edit the specified command CMD_NUMBER;
     With two arguments, edit the list of commands between FIRST and
     LAST.  Command number specifiers may also be negative where -1
     refers to the most recently executed command.  The following are
     equivalent and edit the most recently executed command.

          edit_history
          edit_history -1

     When using ranges, specifying a larger number for the first command
     than the last command reverses the list of commands before they are
     placed in the buffer to be edited.

     See also: *note run_history: XREFrun_history.

 -- Command: run_history
 -- Command: run_history CMD_NUMBER
 -- Command: run_history FIRST LAST
     Run commands from the history list.

     When invoked with no arguments, run the previously executed
     command; With one argument, run the specified command CMD_NUMBER;
     With two arguments, run the list of commands between FIRST and
     LAST.  Command number specifiers may also be negative where -1
     refers to the most recently executed command.  For example, the
     command

          run_history
               OR
          run_history -1

     executes the most recent command again.  The command

          run_history 13 169

     executes commands 13 through 169.

     Specifying a larger number for the first command than the last
     command reverses the list of commands before executing them.  For
     example:

          disp (1)
          disp (2)
          run_history -1 -2
          =>
           2
           1

     See also: *note edit_history: XREFedit_history.

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

 -- Built-in Function: VAL = history_save ()
 -- Built-in Function: OLD_VAL = history_save (NEW_VAL)
 -- Built-in Function: history_save (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: XREFhistory_control, *note
     history_file: XREFhistory_file, *note history_size:
     XREFhistory_size, *note history_timestamp_format_string:
     XREFhistory_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
     'history_save'.

     See also: *note history_file: XREFhistory_file, *note history_size:
     XREFhistory_size, *note history_timestamp_format_string:
     XREFhistory_timestamp_format_string, *note history_save:
     XREFhistory_save.

 -- 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: XREFhistory_size, *note history_save:
     XREFhistory_save, *note history_timestamp_format_string:
     XREFhistory_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 '1000', but may
     be overridden by the environment variable 'OCTAVE_HISTSIZE'.

     See also: *note history_file: XREFhistory_file, *note
     history_timestamp_format_string:
     XREFhistory_timestamp_format_string, *note history_save:
     XREFhistory_save.

 -- 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: XREFstrftime, *note history_file:
     XREFhistory_file, *note history_size: XREFhistory_size, *note
     history_save: XREFhistory_save.

 -- 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 default text
     editor.

     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: XREFedit, *note edit_history:
     XREFedit_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: readline_read_init_file (FILE)
     Read the readline library initialization file FILE.  If FILE is
     omitted, read the default initialization file (normally
     '~/.inputrc').

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

     See also: *note readline_re_read_init_file:
     XREFreadline_re_read_init_file.

 -- Built-in Function: readline_re_read_init_file ()
     Re-read the last readline library initialization file that was
     read.  *Note (readline)Readline Init File::, for details.

     See also: *note readline_read_init_file:
     XREFreadline_read_init_file.


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 "octave:\#> ".
     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: XREFPS2, *note PS4: XREFPS4.

 -- 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: XREFPS1, *note PS4: XREFPS4.

 -- 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: XREFecho, *note echo_executing_commands:
     XREFecho_executing_commands, *note PS1: XREFPS1, *note PS2:
     XREFPS2.


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
 -- Command: diary on
 -- Command: diary off
 -- Command: diary FILENAME
     Record a list of all commands _and_ the output they produce, mixed
     together just as they appear on the terminal.

     Valid options are:

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

     off
          Stop recording the session in the diary file.

     FILENAME
          Record the session in the file named FILENAME.

     With no arguments, 'diary' toggles the current diary state.

     See also: *note history: XREFhistory.

   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 External Code Interface::,
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 a cell array of strings containing all the
     currently installed data types.

     See also: *note class: XREFclass, *note isa: XREFisa.

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

 -- Function File: CLASSNAME = class (OBJ)
 -- Function File: class (S, ID)
 -- Function File: class (S, ID, P, ...)
     Return the class of the object OBJ 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.

     See also: *note typeinfo: XREFtypeinfo, *note isa: XREFisa.

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

     CLASSNAME may also be one of the following class categories:

     "float"
          Floating point value comprising classes "double" and "single".

     "integer"
          Integer value comprising classes (u)int8, (u)int16, (u)int32,
          (u)int64.

     "numeric"
          Numeric value comprising either a floating point or integer
          value.

     See also: *note class: XREFclass, *note typeinfo: XREFtypeinfo.

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

     See also: *note int8: XREFint8, *note uint8: XREFuint8, *note
     int16: XREFint16, *note uint16: XREFuint16, *note int32: XREFint32,
     *note uint32: XREFuint32, *note int64: XREFint64, *note uint64:
     XREFuint64, *note double: XREFdouble.

 -- Built-in 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")
          => [   1,   0, 255, 255]

     See also: *note cast: XREFcast, *note bitunpack: XREFbitunpack,
     *note bitpack: XREFbitpack, *note swapbytes: XREFswapbytes.

 -- 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: XREFtypecast, *note cast: XREFcast.

 -- Built-in 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: XREFbitunpack, *note typecast:
     XREFtypecast.

 -- Built-in 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: XREFbitpack, *note typecast: XREFtypecast.

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

 -- 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: XREFisnan, *note isinf: XREFisinf, *note
     isfinite: XREFisfinite.


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

     See also: *note size: XREFsize.

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

     See also: *note rows: XREFrows, *note size: XREFsize, *note length:
     XREFlength, *note numel: XREFnumel, *note isscalar: XREFisscalar,
     *note isvector: XREFisvector, *note ismatrix: XREFismatrix.

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

     See also: *note columns: XREFcolumns, *note size: XREFsize, *note
     length: XREFlength, *note numel: XREFnumel, *note isscalar:
     XREFisscalar, *note isvector: XREFisvector, *note ismatrix:
     XREFismatrix.

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

 -- Built-in Function: length (A)
     Return the length of the object A.

     The length is 0 for empty objects, 1 for scalars, and the number of
     elements for vectors.  For matrix objects, the length is the number
     of rows or columns, whichever is greater (this odd definition is
     used for compatibility with MATLAB).

     See also: *note numel: XREFnumel, *note size: XREFsize.

 -- 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: XREFnumel, *note ndims: XREFndims, *note
     length: XREFlength, *note rows: XREFrows, *note columns:
     XREFcolumns.

 -- 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: XREFisnull, *note isa: XREFisa.

 -- 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: XREFisempty, *note isindex: XREFisindex.

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

     See also: *note whos: XREFwhos.

 -- 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: XREFsize, *note numel: XREFnumel, *note
     ndims: XREFndims.

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

     See also: *note reshape: XREFreshape.


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

 -- 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: XREFreal, *note imag: XREFimag, *note
     iscomplex: XREFiscomplex, *note abs: XREFabs, *note arg: XREFarg.

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

   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: XREFformat, *note fixed_point_format:
     XREFfixed_point_format, *note output_precision:
     XREFoutput_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: XREFformat, *note fixed_point_format:
     XREFfixed_point_format, *note output_max_field_width:
     XREFoutput_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: XREFformat.

   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.

     The scaled format prints a scaling factor on the first line of
     output chosen such that the largest matrix element can be written
     with a single leading digit.  For example:

          logspace (1, 7, 5)'
          ans =

            1.0e+07  *

            0.00000
            0.00003
            0.00100
            0.03162
            1.00000

     Notice that the first value appears to be 0 when it is actually 1.
     Because of the possibilty for confusion you should be careful about
     enabling 'fixed_point_format'.

     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: XREFformat, *note output_max_field_width:
     XREFoutput_max_field_width, *note output_precision:
     XREFoutput_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: XREFformat.

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

   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: XREFisfloat, *note ischar: XREFischar,
     *note islogical: XREFislogical, *note isnumeric: XREFisnumeric,
     *note isa: XREFisa.

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

     See also: *note uint8: XREFuint8, *note int16: XREFint16, *note
     uint16: XREFuint16, *note int32: XREFint32, *note uint32:
     XREFuint32, *note int64: XREFint64, *note uint64: XREFuint64.

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

     See also: *note int8: XREFint8, *note int16: XREFint16, *note
     uint16: XREFuint16, *note int32: XREFint32, *note uint32:
     XREFuint32, *note int64: XREFint64, *note uint64: XREFuint64.

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

     See also: *note int8: XREFint8, *note uint8: XREFuint8, *note
     uint16: XREFuint16, *note int32: XREFint32, *note uint32:
     XREFuint32, *note int64: XREFint64, *note uint64: XREFuint64.

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

     See also: *note int8: XREFint8, *note uint8: XREFuint8, *note
     int16: XREFint16, *note int32: XREFint32, *note uint32: XREFuint32,
     *note int64: XREFint64, *note uint64: XREFuint64.

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

     See also: *note int8: XREFint8, *note uint8: XREFuint8, *note
     int16: XREFint16, *note uint16: XREFuint16, *note uint32:
     XREFuint32, *note int64: XREFint64, *note uint64: XREFuint64.

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

     See also: *note int8: XREFint8, *note uint8: XREFuint8, *note
     int16: XREFint16, *note uint16: XREFuint16, *note int32: XREFint32,
     *note int64: XREFint64, *note uint64: XREFuint64.

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

     See also: *note int8: XREFint8, *note uint8: XREFuint8, *note
     int16: XREFint16, *note uint16: XREFuint16, *note int32: XREFint32,
     *note uint32: XREFuint32, *note uint64: XREFuint64.

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

     See also: *note int8: XREFint8, *note uint8: XREFuint8, *note
     int16: XREFint16, *note uint16: XREFuint16, *note int32: XREFint32,
     *note uint32: XREFuint32, *note int64: XREFint64.

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

     See also: *note intmin: XREFintmin, *note flintmax: XREFflintmax,
     *note bitmax: XREFbitmax.

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

     See also: *note intmax: XREFintmax, *note flintmax: XREFflintmax,
     *note bitmax: XREFbitmax.

 -- Built-in Function: flintmax ()
 -- Built-in Function: flintmax ("double")
 -- Built-in Function: flintmax ("single")
     Return the largest integer that can be represented consecutively in
     a floating point value.  The default class is "double", but
     "single" is a valid option.  On IEEE-754 compatible systems,
     'flintmax' is 2^53 for "double" and 2^24 for "single".

     See also: *note bitmax: XREFbitmax, *note intmax: XREFintmax, *note
     realmax: XREFrealmax, *note realmin: XREFrealmin.

* 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: XREFldivide, *note rdivide: XREFrdivide.


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.
     All variables must be the same size or scalars.

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

     See also: *note bitand: XREFbitand, *note bitor: XREFbitor, *note
     bitxor: XREFbitxor, *note bitget: XREFbitget, *note bitcmp:
     XREFbitcmp, *note bitshift: XREFbitshift, *note bitmax: XREFbitmax.

 -- 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: XREFbitand, *note bitor: XREFbitor, *note
     bitxor: XREFbitxor, *note bitset: XREFbitset, *note bitcmp:
     XREFbitcmp, *note bitshift: XREFbitshift, *note bitmax: XREFbitmax.

   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
     for "double" and 2^{24} -1 for "single".

     See also: *note flintmax: XREFflintmax, *note intmax: XREFintmax,
     *note realmax: XREFrealmax, *note realmin: XREFrealmin.

   This is the double precision version of the function '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: XREFbitor, *note bitxor: XREFbitxor, *note
     bitset: XREFbitset, *note bitget: XREFbitget, *note bitcmp:
     XREFbitcmp, *note bitshift: XREFbitshift, *note bitmax: XREFbitmax.

 -- 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: XREFbitor, *note bitxor: XREFbitxor, *note
     bitset: XREFbitset, *note bitget: XREFbitget, *note bitcmp:
     XREFbitcmp, *note bitshift: XREFbitshift, *note bitmax: XREFbitmax.

 -- 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: XREFbitand, *note bitor: XREFbitor, *note
     bitset: XREFbitset, *note bitget: XREFbitget, *note bitcmp:
     XREFbitcmp, *note bitshift: XREFbitshift, *note bitmax: XREFbitmax.

   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: XREFbitand, *note bitor: XREFbitor, *note
     bitxor: XREFbitxor, *note bitset: XREFbitset, *note bitget:
     XREFbitget, *note bitcmp: XREFbitcmp, *note bitshift: XREFbitshift,
     *note bitmax: XREFbitmax.

   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: XREFbitand, *note bitor: XREFbitor, *note
     bitxor: XREFbitxor, *note bitset: XREFbitset, *note bitget:
     XREFbitget, *note bitcmp: XREFbitcmp, *note bitmax: XREFbitmax.

   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 the numeric object X to logical type.

     Any non-zero values will be converted to true (1) while zero values
     will be converted to false (0).  The non-numeric value NaN cannot
     be converted and will produce an error.

     Compatibility Note: Octave accepts complex values as input, whereas
     MATLAB issues an error.

     See also: *note double: XREFdouble, *note single: XREFsingle, *note
     char: XREFchar.

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

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


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: XREFisinteger, *note isfloat:
     XREFisfloat, *note isreal: XREFisreal, *note iscomplex:
     XREFiscomplex, *note islogical: XREFislogical, *note ischar:
     XREFischar, *note iscell: XREFiscell, *note isstruct: XREFisstruct,
     *note isa: XREFisa.

 -- 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: XREFisinteger, *note ischar: XREFischar,
     *note islogical: XREFislogical, *note isnumeric: XREFisnumeric,
     *note isa: XREFisa.

 -- 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: XREFiscomplex, *note isnumeric:
     XREFisnumeric, *note isa: XREFisa.

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

     See also: *note isreal: XREFisreal, *note isnumeric: XREFisnumeric,
     *note islogical: XREFislogical, *note ischar: XREFischar, *note
     isfloat: XREFisfloat, *note isa: XREFisa.

 -- 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: XREFisscalar, *note isvector:
     XREFisvector, *note iscell: XREFiscell, *note isstruct:
     XREFisstruct, *note issparse: XREFissparse, *note isa: XREFisa.

 -- 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: XREFisscalar, *note ismatrix:
     XREFismatrix, *note size: XREFsize, *note rows: XREFrows, *note
     columns: XREFcolumns, *note length: XREFlength.

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

     See also: *note iscolumn: XREFiscolumn, *note isscalar:
     XREFisscalar, *note isvector: XREFisvector, *note ismatrix:
     XREFismatrix.

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

     See also: *note isrow: XREFisrow, *note isscalar: XREFisscalar,
     *note isvector: XREFisvector, *note ismatrix: XREFismatrix.

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

     See also: *note isvector: XREFisvector, *note ismatrix:
     XREFismatrix.

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

     See also: *note isscalar: XREFisscalar, *note isvector:
     XREFisvector, *note ismatrix: XREFismatrix, *note size: XREFsize.

 -- 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: XREFishermitian, *note isdefinite:
     XREFisdefinite.

 -- 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: XREFissymmetric, *note isdefinite:
     XREFisdefinite.

 -- 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: XREFissymmetric, *note ishermitian:
     XREFishermitian.

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

     See also: *note isfloat: XREFisfloat, *note isinteger:
     XREFisinteger, *note ischar: XREFischar, *note isnumeric:
     XREFisnumeric, *note isa: XREFisa.

 -- 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: XREFprimes, *note factor: XREFfactor, *note
     gcd: XREFgcd, *note lcm: XREFlcm.

   If instead of knowing properties of variables, you wish to know which
variables are defined and to gather other information about the
workspace itself, *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 null 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.

'\NNN'
     Represents the octal value NNN, where NNN are one to three digits
     between 0 and 7.  For example, the code for the ASCII ESC (escape)
     character is '\033'.

'\xHH...'
     Represents the hexadecimal value HH, where HH are hexadecimal
     digits ('0' through '9' and either 'A' through 'F' or 'a' through
     'f').  Like the same construct in ANSI C, the escape sequence
     continues until the first non-hexadecimal digit is seen.  However,
     using more than two hexadecimal digits produces undefined results.

   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: XREFis_sq_string, *note ischar:
     XREFischar.

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

     See also: *note is_dq_string: XREFis_dq_string, *note ischar:
     XREFischar.


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: XREFisfloat, *note isinteger:
     XREFisinteger, *note islogical: XREFislogical, *note isnumeric:
     XREFisnumeric, *note iscellstr: XREFiscellstr, *note isa: XREFisa.

   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)
          => 1

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

     ischar ("my string") && isvector ("my string")
          => 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: XREFrepmat.

* Menu:

* Concatenating Strings::
* Converting Numerical Data to Strings::


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

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

Strings can be concatenated using matrix notation (*note Strings::,
*note Character Arrays::) which is often the most natural method.  For
example:

     fullname = [fname ".txt"];
     email = ["<" user "@" domain ">"];

In each case it is easy to see what the final string will look like.
This method is also the most efficient.  When using matrix concatenation
the parser immediately begins joining the strings without having to
process the overhead of a function call and the input validation of the
associated function.

   Nevertheless, there are several other functions for concatenating
string objects which can be useful in specific circumstances: 'char',
'strvcat', 'strcat', and 'cstrcat'.  Finally, the general purpose
concatenation functions can be used: see *note cat: XREFcat, *note
horzcat: XREFhorzcat, and *note vertcat: XREFvertcat.

   * 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])
             => banana

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

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

          strcat ("oc", "tave", " is", " good", " for you")
               => 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")
              => orange
                 green

                 red

          strvcat ("orange", "green", "", "red")
              => 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"})
               => red
                  green

                  blue

          strcat ({"abc"; "ghi"}, {"def"; "jkl"})
               =>
                  {
                    [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"])
               => dir1/file1
                  directory2/file2

          cstrcat (["thirteen apples"; "a banana"], [" 5$";" 1$"])
                => 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: XREFstrvcat, *note cellstr: XREFcellstr.

 -- 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: XREFchar, *note strcat: XREFstrcat, *note
     cstrcat: XREFcstrcat.

 -- Function File: strcat (S1, S2, ...)
     Return a string containing all the arguments concatenated
     horizontally.  If the arguments are cell 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 for any character string
     input is eliminated before the strings are concatenated.  Note that
     cell string values do *not* have whitespace trimmed.

     For example:

          strcat ("|", " leading space is preserved", "|")
              => | leading space is preserved|

          strcat ("|", "trailing space is eliminated ", "|")
              => |trailing space is eliminated|

          strcat ("homogeneous space |", "  ", "| is also eliminated")
              => homogeneous space || is also eliminated

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

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

     See also: *note cstrcat: XREFcstrcat, *note char: XREFchar, *note
     strvcat: XREFstrvcat.

 -- 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: XREFstrcat, *note char: XREFchar, *note
     strvcat: XREFstrvcat.


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

5.3.2 Converting 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 sprintf: XREFsprintf.).

 -- 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: XREFsprintf, *note num2str: XREFnum2str,
     *note int2str: XREFint2str.

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

     Examples:

          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"

     Notes:

     For MATLAB compatibility, leading spaces are stripped before
     returning the string.

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

     For complex X, the format string may only contain one output
     conversion specification and nothing else.  Otherwise, results will
     be unpredictable.

     See also: *note sprintf: XREFsprintf, *note int2str: XREFint2str,
     *note mat2str: XREFmat2str.

 -- 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
               =>
                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: XREFsprintf, *note num2str: XREFnum2str,
     *note mat2str: XREFmat2str.


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: XREFstrcmpi, *note strncmp: XREFstrncmp,
     *note strncmpi: XREFstrncmpi.

 -- 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: XREFstrncmpi, *note strcmp: XREFstrcmp,
     *note strcmpi: XREFstrcmpi.

 -- 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: XREFstrcmp, *note strncmp: XREFstrncmp,
     *note strncmpi: XREFstrncmpi.

 -- 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: XREFstrncmp, *note strcmp: XREFstrcmp,
     *note strcmpi: XREFstrcmpi.

 -- 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: XREFstrcmp, *note strcmpi: XREFstrcmpi.


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

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

 -- 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: XREFstrfind, *note strmatch: XREFstrmatch,
     *note strcmp: XREFstrcmp, *note strncmp: XREFstrncmp, *note
     strcmpi: XREFstrcmpi, *note strncmpi: XREFstrncmpi, *note find:
     XREFfind.

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

 -- 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: XREFfind, *note rindex: XREFrindex.

 -- 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: XREFfind, *note index: XREFindex.

 -- Built-in Function: IDX = strfind (STR, PATTERN)
 -- Built-in Function: IDX = strfind (CELLSTR, PATTERN)
 -- Built-in Function: IDX = strfind (..., "overlaps", VAL)
     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 '[]'.  The optional argument "overlaps"
     determines whether the pattern can match at every position in STR
     (true), or only for unique occurrences of the complete pattern
     (false).  The default is true.

     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", "aba", "overlaps", false)
               => [1, 5]

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

                       1   3   5

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

     See also: *note findstr: XREFfindstr, *note strmatch: XREFstrmatch,
     *note regexp: XREFregexp, *note regexpi: XREFregexpi, *note find:
     XREFfind.

 -- Function File: STR = strjoin (CSTR)
 -- Function File: STR = strjoin (CSTR, DELIMITER)
     Join the elements of the cell string array, CSTR, into a single
     string.

     If no DELIMITER is specified, the elements of CSTR separated by a
     space.

     If DELIMITER is specified as a string, the cell string array is
     joined using the string.  Escape sequences are supported.

     If DELIMITER is a cell string array whose length is one less than
     CSTR, then the elements of CSTR are joined by interleaving the cell
     string elements of DELIMITER.  Escape sequences are not supported.

          strjoin ({'Octave','Scilab','Lush','Yorick'}, '*')
                => 'Octave*Scilab*Lush*Yorick'

     See also: strsplit.

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

     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 'strncmp'
     (normal case), or 'strcmp' ("exact" case), or 'regexp' in all new
     code.

     See also: *note strfind: XREFstrfind, *note findstr: XREFfindstr,
     *note strcmp: XREFstrcmp, *note strncmp: XREFstrncmp, *note
     strcmpi: XREFstrcmpi, *note strncmpi: XREFstrncmpi, *note find:
     XREFfind.

 -- 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: XREFindex, *note strsplit: XREFstrsplit,
     *note strchr: XREFstrchr, *note isspace: XREFisspace.

 -- Function File: [CSTR] = strsplit (S)
 -- Function File: [CSTR] = strsplit (S, DEL)
 -- Function File: [CSTR] = strsplit (..., NAME, VALUE)
 -- Function File: [CSTR, MATCHES] = strsplit (...)
     Split the string S using the delimiters specified by DEL and return
     a cell string array of substrings.  If a delimiter is not specified
     the string, S, is split at whitespace.  The delimiter, DEL may be a
     string, a scalar cell string, or cell string array.  By default,
     consecutive delimiters in the input string S are collapsed into
     one.

     The second output, MATCHES, returns the delimiters which were
     matched in the original string.

     Example:

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

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

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

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


     Supported NAME/VALUE pair arguments are;

        * COLLAPSEDELIMITERS may take the value of TRUE or FALSE with
          the default being FALSE.

        * DELIMITERTYPE may take the value of 'simple' or
          'regularexpression'.  The default is DELIMITERTYPE is
          'simple'.

     Example:

          strsplit ("a foo b,bar c", ",|\\s|foo|bar", "delimitertype", "regularexpression")
                =>
                    {
                      [1,1] = a
                      [1,2] = b
                      [1,3] = c
                    }

          strsplit ("a,,b, c", "[, ]", false, "delimitertype", "regularexpression")
                =>
                    {
                      [1,1] = a
                      [1,2] =
                      [1,3] = b
                      [1,4] =
                      [1,5] = c
                    }

          strsplit ("a,\t,b, c", {',', '\s'}, "delimitertype", "regularexpression")
                =>
                    {
                      [1,1] = a
                      [1,2] = b
                      [1,3] = c
                    }

          strsplit ("a,\t,b, c", {',', ' ', '\t'}, "collapsedelimiters", false)
                =>
                    {
                      [1,1] = a
                      [1,2] =
                      [1,3] =
                      [1,4] = b
                      [1,5] =
                      [1,6] = c
                    }

     See also: *note ostrsplit: XREFostrsplit, *note strjoin:
     XREFstrjoin, *note strtok: XREFstrtok, *note regexp: XREFregexp.

 -- Function File: [CSTR] = ostrsplit (S, SEP)
 -- Function File: [CSTR] = ostrsplit (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:

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

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

     See also: *note strsplit: XREFstrsplit, *note strtok: XREFstrtok.

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

     When the number of words in STR doesn't match an exact multiple of
     the number of format conversion specifiers, strread's behavior
     depends on the last character of STR:

     last character = "\n"
          Data columns are padded with empty fields or Nan so that all
          columns have equal length

     last character is not "\n"
          Data columns are not padded; strread returns columns of
          unequal length

     See also: *note textscan: XREFtextscan, *note textread:
     XREFtextread, *note load: XREFload, *note dlmread: XREFdlmread,
     *note fscanf: XREFfscanf.

 -- Built-in Function: NEWSTR = strrep (STR, PTN, REP)
 -- Built-in Function: NEWSTR = strrep (CELLSTR, PTN, REP)
 -- Built-in Function: NEWSTR = strrep (..., "overlaps", VAL)
     Replace all occurrences of the pattern PTN in the string STR with
     the string REP and return the result.

     The optional argument "overlaps" determines whether the pattern can
     match at every position in STR (true), or only for unique
     occurrences of the complete pattern (false).  The default is true.

     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.

     Example:

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

     See also: *note regexprep: XREFregexprep, *note strfind:
     XREFstrfind, *note findstr: XREFfindstr.

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

 -- Built-in Function: [S, E, TE, M, T, NM, SP] = regexp (STR, PAT)
 -- Built-in 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.  The first form, parentheses only, also
          creates a token.

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

     '\d'
          Match any digit

     '\D'
          Match any non-digit

     '\s'
          Match any whitespace character

     '\S'
          Match any non-whitespace character

     '\w'
          Match any word character

     '\W'
          Match any non-word character

     '\<'
          Match the beginning of a word

     '\>'
          Match the end of a word

     '\B'
          Match within a word

     Implementation Note: For compatibility with MATLAB, ordinary escape
     sequences (e.g., "\n" => newline) are processed in PAT regardless
     of whether PAT has been defined within single quotes.  Use a second
     backslash to stop interpolation of the escape sequence (e.g.,
     "\\n") or use the 'regexptranslate' function.

     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, i.e., what
          remains if you split the string based on PAT.

     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.

     'noemptymatch'
          Zero-length matches are not returned.  (default)

     'emptymatch'
          Return zero-length matches.

          'regexp ('a', 'b*', 'emptymatch')' returns '[1 2]' because
          there are zero or more 'b' characters at positions 1 and
          end-of-string.

     See also: *note regexpi: XREFregexpi, *note strfind: XREFstrfind,
     *note regexprep: XREFregexprep.

 -- Built-in Function: [S, E, TE, M, T, NM, SP] = regexpi (STR, PAT)
 -- Built-in 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: XREFregexp, for
     details on the syntax of the search pattern.

     See also: *note regexp: XREFregexp.

 -- Built-in Function: OUTSTR = regexprep (STRING, PAT, REPSTR)
 -- Built-in 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: XREFregexp.

     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.

     Implementation Note: For compatibility with MATLAB, ordinary escape
     sequences (e.g., "\n" => newline) are processed in both PAT and
     REPSTR regardless of whether they were defined within single
     quotes.  Use a second backslash to stop interpolation of the escape
     sequence (e.g., "\\n") or use the 'regexptranslate' function.

     See also: *note regexp: XREFregexp, *note regexpi: XREFregexpi,
     *note strrep: XREFstrrep.

 -- 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: XREFregexp, *note regexpi: XREFregexpi,
     *note regexprep: XREFregexprep.

 -- 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: XREFstrjust, *note strsplit: XREFstrsplit,
     *note deblank: XREFdeblank.


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")
           => 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: XREFdec2bin, *note base2dec: XREFbase2dec,
     *note hex2dec: XREFhex2dec.

 -- 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: XREFbin2dec, *note dec2base: XREFdec2base,
     *note dec2hex: XREFdec2hex.

 -- 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: XREFhex2dec, *note dec2base: XREFdec2base,
     *note dec2bin: XREFdec2bin.

 -- 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: XREFdec2hex, *note base2dec: XREFbase2dec,
     *note bin2dec: XREFbin2dec.

 -- 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: XREFbase2dec, *note dec2bin: XREFdec2bin,
     *note dec2hex: XREFdec2hex.

 -- 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: XREFdec2base, *note bin2dec: XREFbin2dec,
     *note hex2dec: XREFhex2dec.

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

          num2hex ([-1, 1, e, Inf])
          => "bff0000000000000
              3ff0000000000000
              4005bf0a8b145769
              7ff0000000000000"

     If the argument N is a single precision number or vector, the
     returned string has a length of 8.  For example:

          num2hex (single ([-1, 1, e, Inf]))
          => "bf800000
              3f800000
              402df854
              7f800000"

     See also: *note hex2num: XREFhex2num, *note hex2dec: XREFhex2dec,
     *note dec2hex: XREFdec2hex.

 -- Built-in Function: N = hex2num (S)
 -- Built-in Function: N = hex2num (S, CLASS)
     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]

     The optional argument CLASS can be passed as the string "single" to
     specify that the given string should be interpreted as a single
     precision number.  In this case, S should be an 8 character
     hexadecimal string.  For example:

          hex2num (["402df854"; "41200000"], "single")
             => [2.7183; 10.000]

     See also: *note num2hex: XREFnum2hex, *note hex2dec: XREFhex2dec,
     *note dec2hex: XREFdec2hex.

 -- 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 be a character string, character matrix, or cell array.  For
     character arrays the conversion is repeated for every row, and a
     double or complex array is returned.  Empty rows in S are deleted
     and not returned in the numeric array.  For cell arrays each
     character string element is processed and a double or complex array
     of the same dimensions as S is returned.

     For unconvertible scalar or character string input 'str2double'
     returns a NaN.  Similarly, for character array input 'str2double'
     returns a NaN for any row of S that could not be converted.  For a
     cell array, 'str2double' returns a NaN for any element of S for
     which conversion fails.  Note that numeric elements in a mixed
     string/numeric cell array are not strings and the conversion will
     fail for these elements and return NaN.

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

     See also: *note str2num: XREFstr2num.

 -- 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: XREFdeblank, *note strrep: XREFstrrep,
     *note strtrim: XREFstrtrim, *note untabify: XREFuntabify.

 -- 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: XREFstr2double, *note eval: XREFeval.

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

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

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

 -- 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: XREFisalpha, *note isdigit: XREFisdigit,
     *note ispunct: XREFispunct, *note isspace: XREFisspace, *note
     iscntrl: XREFiscntrl.

 -- 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: XREFisdigit, *note ispunct: XREFispunct,
     *note isspace: XREFisspace, *note iscntrl: XREFiscntrl, *note
     isalnum: XREFisalnum, *note islower: XREFislower, *note isupper:
     XREFisupper.

 -- 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: XREFisalpha, *note isdigit: XREFisdigit,
     *note ispunct: XREFispunct, *note isspace: XREFisspace, *note
     iscntrl: XREFiscntrl, *note isalnum: XREFisalnum.

 -- 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: XREFisupper, *note isalpha: XREFisalpha,
     *note isletter: XREFisletter, *note isalnum: XREFisalnum.

 -- 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: XREFislower, *note isalpha: XREFisalpha,
     *note isletter: XREFisletter, *note isalnum: XREFisalnum.

 -- 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: XREFisxdigit, *note isalpha: XREFisalpha,
     *note isletter: XREFisletter, *note ispunct: XREFispunct, *note
     isspace: XREFisspace, *note iscntrl: XREFiscntrl.

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

 -- 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: XREFisalpha, *note isdigit: XREFisdigit,
     *note isspace: XREFisspace, *note iscntrl: XREFiscntrl.

 -- 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: XREFiscntrl, *note ispunct: XREFispunct,
     *note isalpha: XREFisalpha, *note isdigit: XREFisdigit.

 -- 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: XREFispunct, *note isspace: XREFisspace,
     *note isalpha: XREFisalpha, *note isdigit: XREFisdigit.

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

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

 -- 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: XREFisalpha, *note isalnum: XREFisalnum,
     *note islower: XREFislower, *note isupper: XREFisupper, *note
     isdigit: XREFisdigit, *note isxdigit: XREFisxdigit, *note isspace:
     XREFisspace, *note ispunct: XREFispunct, *note iscntrl:
     XREFiscntrl, *note isgraph: XREFisgraph, *note isprint:
     XREFisprint, *note isascii: XREFisascii.


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.

     See also: *note print_struct_array_contents:
     XREFprint_struct_array_contents.

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

     See also: *note struct_levels_to_print: XREFstruct_levels_to_print.

   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
             }

Dynamic indexing also allows you to use arbitrary strings, not merely
valid Octave identifiers (note that this does not work on MATLAB):

     a = "long field with spaces (and funny char$)";
     x.a = 1;
     x.(a) = 2;
     x
          => x =
             {
               a =  1
               long field with spaces (and funny char$) =  2
             }

The warning id 'Octave:matlab-incompatible' can be enabled to warn about
this usage.  *Note warning_ids: XREFwarning_ids.

   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: S = struct ()
 -- Built-in Function: S = struct (FIELD1, VALUE1, FIELD2, VALUE2, ...)
 -- Built-in Function: S = struct (OBJ)

     Create a scalar or array structure and initialize its values.  The
     FIELD1, FIELD2, ... variables are strings specifying the names of
     the fields and the VALUE1, VALUE2, ... variables can be of any
     type.

     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.

     Observe that the syntax is optimized for struct *arrays*.  Consider
     the following examples:

          struct ("foo", 1)
            => scalar structure containing the fields:
              foo =  1

          struct ("foo", {})
            => 0x0 struct array containing the fields:
              foo

          struct ("foo", { {} })
            => scalar structure containing the fields:
              foo = {}(0x0)

          struct ("foo", {1, 2, 3})
            => 1x3 struct array containing the fields:
              foo


     The first case is an ordinary scalar struct--one field, one value.
     The second produces an empty struct array with one field and no
     values, since s being passed an empty cell array of struct array
     values.  When the value is a cell array containing a single entry,
     this becomes a scalar struct with that single entry as the value of
     the field.  That single entry happens to be an empty cell array.

     Finally, if the value is a non-scalar cell array, then 'struct'
     produces a struct *array*.

     See also: *note cell2struct: XREFcell2struct, *note fieldnames:
     XREFfieldnames, *note orderfields: XREForderfields, *note getfield:
     XREFgetfield, *note setfield: XREFsetfield, *note rmfield:
     XREFrmfield, *note structfun: XREFstructfun.

   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: XREFismatrix, *note iscell: XREFiscell,
     *note isa: XREFisa.


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.

     See also: *note fieldnames: XREFfieldnames.

 -- Function File: NAMES = fieldnames (STRUCT)
 -- Function File: NAMES = fieldnames (OBJ)
 -- Function File: NAMES = fieldnames (JAVAOBJ)
 -- Function File: NAMES = fieldnames ("JCLASSNAME")
     Return a cell array of strings with the names of the fields in the
     specified input.

     When the input is a structure STRUCT, the names are the elements of
     the structure.

     When the input is an Octave object OBJ, the names are the public
     properties of the object.

     When the input is a Java object JAVAOBJ or Java classname
     JCLASSNAME the name are the public data elements of the object or
     class.

     See also: *note nfields: XREFnfields, *note isfield: XREFisfield,
     *note orderfields: XREForderfields, *note struct: XREFstruct, *note
     methods: XREFmethods.

 -- Built-in Function: isfield (X, "NAME")
 -- 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.

     See also: *note fieldnames: XREFfieldnames.

 -- Function File: S = setfield (S, FIELD, VAL)
 -- Function File: S = setfield (S, IDX1, FIELD1, IDX2, FIELD2, ...,
          VAL)

     Set a field member FIELD in a structure S equal to VAL.  For
     example:

          S = struct ();
          S = setfield (S, "foo bar", 42);

     This is equivalent to

          S.("foo bar") = 42;

     Note that ordinary structure syntax 'S.foo bar = 42' cannot be used
     here, as the field name is not a valid Octave identifier.  Using
     arbitrary strings for field name is incompatible with MATLAB, so
     this usage will warn if the 'Octave:matlab-incompatible' warning is
     set.  *Note XREFwarning_ids::.

     With the second calling form, set a field on a structure array,
     possibly nested, with successive nested indices IDX1, IDX2, ... and
     fields FIELD1, FIELD2, ... The indices must be cells containing the
     desired index at this nesting depth.

     Thus consider instead,

          S = struct ("baz", 42);
          setfield (S, {1}, "foo", {1}, "bar", 5)
              => ans =
              scalar structure containing the fields:
                baz =  42
                foo =
                  scalar structure containing the fields:
                    bar =  54

     Here we first have an ordinary structure array with one field 'baz'
     set to 42.  Then we set another field in a nested scalar structure
     indexing with two single cells containing the unique desired
     indices.

     Finally an example with nested structure arrays,

          SA.foo = 1;
          SA = setfield (SA, {2}, "bar", {3}, "baz", 6);
          SA(2).bar(3)
               => ans =
               scalar structure containing the fields:
                 baz =  6

     Here SA is a structure array whose field 'fd' at elements 1 and 2
     field is in turn another structure array whose third element is a
     structure

     Note that the same result as in the above example could be achieved
     by:

          SA.foo = 1;
          SA(2).bar(3).baz = 6

     See also: *note getfield: XREFgetfield, *note rmfield: XREFrmfield,
     *note isfield: XREFisfield, *note fieldnames: XREFfieldnames, *note
     isstruct: XREFisstruct, *note struct: XREFstruct.

 -- Function File: [VAL] = getfield (S, FIELD)
 -- Function File: [VAL] = getfield (S, IDX1, FIELD1, IDX2, FIELD2, ...)
     Extract a field from a structure (or a nested structure).  The
     syntax is the same as 'setfield', except it omits the final VAL
     argument, returning this value instead of setting it.

     See also: *note setfield: XREFsetfield, *note rmfield: XREFrmfield,
     *note isfield: XREFisfield, *note fieldnames: XREFfieldnames, *note
     isstruct: XREFisstruct, *note struct: XREFstruct.

 -- Built-in Function: S = rmfield (S, "F")
 -- Built-in Function: S = 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 each of the named fields.

     See also: *note orderfields: XREForderfields, *note fieldnames:
     XREFfieldnames.

 -- 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: XREFgetfield, *note rmfield: XREFrmfield,
     *note isfield: XREFisfield, *note isstruct: XREFisstruct, *note
     fieldnames: XREFfieldnames, *note struct: XREFstruct.

 -- 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: XREFsubsref, *note subsasgn: XREFsubsasgn.


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

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

 -- Built-in Function: C = 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 = {2x1x3 Cell Array}
          c(1,1,:)(:)
             =>
                {
                  [1,1] = Peter
                  [2,1] = Hannah
                  [3,1] = Robert
                }
          c(2,1,:)(:)
             =>
                {
                  [1,1] = 23
                  [2,1] = 16
                  [3,1] = 3
                }

     See also: *note cell2struct: XREFcell2struct, *note fieldnames:
     XREFfieldnames.


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

   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: XREFismatrix, *note isstruct:
     XREFisstruct, *note iscellstr: XREFiscellstr, *note isa: XREFisa.


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

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: XREFsize. function also works for cell
arrays.  As do other functions describing the size of an object, such as
*note length: XREFlength, *note numel: XREFnumel, *note rows: XREFrows,
and *note columns: XREFcolumns.

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

     See also: *note cellstr: XREFcellstr, *note mat2cell: XREFmat2cell,
     *note num2cell: XREFnum2cell, *note struct2cell: XREFstruct2cell.

   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.

 -- Built-in Function: C = num2cell (A)
 -- Built-in 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])
             =>
                {
                  [1,1] =  1
                  [2,1] =  3
                  [1,2] =  2
                  [2,2] =  4
                }
          num2cell ([1,2;3,4],1)
             =>
                {
                  [1,1] =
                     1
                     3
                  [1,2] =
                     2
                     4
                }

     See also: *note mat2cell: XREFmat2cell.

 -- Built-in Function: C = mat2cell (A, M, N)
 -- Built-in Function: C = mat2cell (A, D1, D2, ...)
 -- Built-in 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: XREFnum2cell, *note cell2mat:
     XREFcell2mat.

 -- Built-in 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: XREFcell2mat, *note cellindexmat:
     XREFcellindexmat, *note cellfun: XREFcellfun.


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"; "x", "y", "z"; "4", "5", "6"};
     c{2,3}
          => ans = z

     c(2,3)
          => ans =
             {
               [1,1] = z
             }

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.

 -- Built-in 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: XREFcellslices, *note cellfun:
     XREFcellfun.


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: CSTR = cellstr (STRMAT)
     Create a new cell array object from the elements of the string
     array STRMAT.

     Each row of STRMAT becomes an element of CSTR.  Any trailing spaces
     in a row are deleted before conversion.

     To convert back from a cellstr to a character array use 'char'.

     See also: *note cell: XREFcell, *note char: XREFchar.

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


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

   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; or structs; and
     'cat' must be able to concatenate them together.

     See also: *note mat2cell: XREFmat2cell, *note num2cell:
     XREFnum2cell.

 -- Built-in Function: cell2struct (CELL, FIELDS)
 -- 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)
             =>
                {
                  Name   = Peter
                  Height = 185
                }


     See also: *note struct2cell: XREFstruct2cell, *note cell2mat:
     XREFcell2mat, *note struct: XREFstruct.


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: XREFiskeyword, *note exist: XREFexist,
     *note who: XREFwho.

 -- 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: XREFisvarname, *note exist: XREFexist,
     *note tmpnam: XREFtmpnam, *note eval: XREFeval.

 -- 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: XREFisvarname, *note exist: XREFexist.


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 (*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: XREFwhos, *note isglobal: XREFisglobal, *note
     isvarname: XREFisvarname, *note exist: XREFexist, *note regexp:
     XREFregexp.

 -- 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: XREFwho, *note whos_line_format:
     XREFwhos_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: XREFwhos.

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

     "dir"
          Check only for directories.

     See also: *note file_in_loadpath: XREFfile_in_loadpath, *note
     file_in_path: XREFfile_in_path, *note find_dir_in_path:
     XREFfind_dir_in_path, *note stat: XREFstat.

   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: text = type ("NAME", ...)
     Display the contents of NAME which may be a file, function
     (m-file), variable, operator, or keyword.

     'type' normally prepends a header line describing the category of
     NAME such as function or variable; The '-q' option suppresses this
     behavior.

     If no output variable is used the contents are displayed on screen.
     Otherwise, a cell array of strings is returned, where each element
     corresponds to the contents 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: XREFhelp, *note lookfor: XREFlookfor.

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

