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

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

END-INFO-DIR-ENTRY

   Copyright © 1996-2018 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 4.3.91.

* Menu:

* Preface::
* Introduction::                A brief introduction to Octave.
* Getting Started::
* Data Types::
* Numeric Data Types::
* Strings::
* Data Containers::
* Variables::
* Expressions::
* Evaluation::
* Statements::                  Looping and program flow control.
* Functions and Scripts::
* Errors and Warnings::
* Debugging::
* Input and Output::
* Plotting::
* Matrix Manipulation::
* Arithmetic::
* Linear Algebra::
* Vectorization and Faster Code Execution::
* Nonlinear Equations::
* Diagonal and Permutation Matrices::
* Sparse Matrices::
* Numerical Integration::
* Differential Equations::
* Optimization::
* Statistics::
* Sets::
* Polynomial Manipulations::
* Interpolation::
* Geometry::
* Signal Processing::
* Image Processing::
* Audio Processing::
* Object Oriented Programming::
* GUI Development::
* System Utilities::
* Packages::
* External Code Interface::
* Test and Demo Functions::
* Obsolete Functions::
* Trouble::                     If you have trouble installing Octave.
* Installation::                How to configure, compile and install Octave.
* 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.
* Graphics Properties Index::   An item for each graphics object property.

 — 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::
* containers.Map::
* 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::
* Access via Handle::

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

Script Files

* Publish Octave Script Files::
* Publishing Markup::

Publishing Markup

* Using Publishing Markup in Script Files::
* Text Formatting::
* Sections::
* Preformatted Code::
* Preformatted Text::
* Bulleted Lists::
* Numbered Lists::
* Including File Content::
* Including Graphics::
* Including URLs::
* Mathematical Equations::
* HTML Markup::
* LaTeX Markup::

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 Objects::
* 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::
* Light Properties::
* Uimenu Properties::
* Uibuttongroup Properties::
* Uicontextmenu Properties::
* Uipanel Properties::
* Uicontrol Properties::
* Uitoolbar Properties::
* Uipushtool Properties::
* Uitoggletool Properties::

Advanced Plotting

* Colors::
* Line Styles::
* Marker Styles::
* Callbacks::
* Application-defined Data::
* Object Groups::
* Transform 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::

Ordinary Differential Equations

* Matlab-compatible solvers::

Optimization

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

Statistics

* Descriptive Statistics::
* Basic Statistical Functions::
* Correlation and Regression Analysis::
* Distributions::
* 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::

Audio Processing

* Audio File Utilities::
* Audio Device Information::
* Audio Player::
* Audio Recorder::
* Audio Data Processing::

Audio Player

* Playback::
* Player Properties::

Audio Recorder

* Recording::
* Data Retrieval::
* Recorder Properties::

Object Oriented Programming

* Creating a Class::
* Class Methods::
* 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::
* UI Elements::
* 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::

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

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

Java Interface

* Making Java Classes Available::
* How to use Java from within Octave::
* Passing parameters to the JVM::
* Java Interface Functions::

Test and Demo Functions

* Test Functions::
* Demonstration Functions::

Trouble

* Actual Bugs::                 Bugs we will fix later.
* Reporting Bugs::
* How To Get Help with Octave::
* How to Distinguish Between Octave and Matlab::

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

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               Drew Abbot               NVS Abhilash
Andy Adler               Adam H. Aitkenhead       Joakim Andén
Giles Anderson           Joel Andersson           Lachlan Andrew
Pedro Angelo             Damjan Angelovski        Muthiah Annamalai
Markus Appel             Branden Archer           Willem Atsma
Marco Atzeri             Ander Aurrekoetxea       Shai Ayal
Sahil Badyal             Jeff Bai                 Roger Banks
Ben Barrowes             Alexander Barth          David Bateman
Heinz Bauschke           Miguel Bazdresch         Julien Bect
Stefan Beller            Roman Belov              Markus Bergholz
Karl Berry               Atri Bhattacharya        Ethan Biery
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
Marco Cecchetti          Corbin Champion          Clinton Chee
Albert Chin-A-Young      Sunghyun Cho             Carsten Clark
Catalin Codreanu         J. D. Cole               Jacopo Corno
Andre da Costa Barros    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              Sergey Dudoladov         Pascal A. Dupuis
John W. Eaton            Dirk Eddelbuettel        Pieter Eendebak
Paul Eggert              Stephen Eglen            Peter Ekberg
Garrett Euler            Edmund Grimley Evans     Rolf Fabian
Francesco Faccio         Gunnar Farnebäck         Massimiliano Fasi
Stephen Fegan            Ramon Garcia Fernandez   Torsten Finke
David Finkel             Guillaume Flandin        Colin Foster
Jose Daniel Munoz        Brad Froehle             Castor Fu
Frias
Eduardo Gallestey        Walter Gautschi          Klaus Gebhardt
Driss Ghaddab            Eugenio Gianniti         Hartmut Gimpel
Michele Ginesi           Nicolo Giorgetti         Arun Giridhar
Michael D. Godfrey       Michael Goffioul         Glenn Golden
Tomislav Goles           Keith Goodman            Brian Gough
Alexander Graf           Michael C. Grant         Steffen Groot
Etienne Grossmann        David Grundberg          Kyle Guinn
Vaibhav Gupta            Peter Gustafson          Kai Habel
Patrick Häcker           William P. Y.            Jaroslav Hajek
                         Hadisoeseno
Benjamin Hall            Alexander Hansen         Kim Hansen
Søren Hauberg            Dave Hawthorne           Oliver Heimlich
Daniel Heiserer          Piotr Held               Martin Helm
Stefan Hepp              Martin Hepperle          Jordi Gutiérrez
                                                  Hermoso
Israel Herraiz           Yozo Hida                Ryan Hinton
Roman Hodek              A. Scottedward Hodel     Richard Allan Holcombe
Tom Holroyd              David Hoover             Kurt Hornik
Craig Hudson             Christopher Hulbert      Cyril Humbert
John Hunt                Stefan Husmann           Teemu Ikonen
Alan W. Irwin            Allan Jacobs             Geoff Jacobsen
Vytautas Jančauskas      Nicholas R. Jankowski    Mats Jansson
Robert Jenssen           Cai Jianming             Steven G. Johnson
Heikki Junes             Matthias Jüschke         Atsushi Kajita
Jarkko Kaleva            Avinoam Kalma            Mohamed Kamoun
Lute Kamstra             Fotios Kasolis           Thomas Kasper
Joel Keay                Mumit Khan               Paul Kienzle
Lars Kindermann          Aaron A. King            Erik Kjellson
Arno J. Klaassen         Alexander Klein          Lasse Kliemann
Geoffrey Knauth          Heine Kolltveit          Ken Kouno
Kacper Kowalik           Endre Kozma              Daniel Kraft
Nir Krakauer             Aravindh                 Oyvind Kristiansen
                         Krishnamoorthy
Artem Krosheninnikov     Piotr Krzyzanowski       Volker Kuhlmann
Ilya Kurdyukov           Tetsuro Kurita           Ben Kurtz
Philipp Kutin            Miroslaw Kwasniak        Rafael Laboissiere
Kai Labusch              Claude Lacoursiere       Walter Landry
Bill Lash                Dirk Laurie              Maurice LeBrun
Friedrich Leisch         Michael Leitner          Johannes Leuschner
Thorsten Liebig          Torsten Lilge            Jyh-miin Lin
Timo Lindfors            Benjamin Lindner         Ross Lippert
Yu Liu                   David Livings            Barbara Locsi
Sebastien Loisel         Erik de Castro Lopo      Massimo Lorenzin
Emil Lucretiu            Yi-Hong Lyu              Hoxide Ma
Colin Macdonald          James Macnicol           Jens-Uwe Mager
Stefan Mahr              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
Stefan Miereis           Petr Mikulik             Mike Miller
Serviscope Minor         Stefan Monnier           Rafael Monteiro
Stephen                  Antoine Moreau           Kai P. Mueller
Montgomery-Smith
Amod Mulay               Armin Müller             Hannes Müller
Victor Munoz             PrasannaKumar            Iain Murray
                         Muralidharan
Nicholas Musolino        Markus Mützel            Carmen Navarrete
Todd Neal                Philip Nienhuis          Al Niessner
Felipe G. Nievinski      Rick Niles               Takuji Nishimura
Akira Noda               Kai Noda                 Patrick Noffke
Victor Norton            Eric Norum               Krzesimir Nowak
Michael O’Brien          Cillian O’Driscoll       Peter O’Gorman
Thorsten Ohl             Kai T. Ohlhus            Arno Onken
Valentin                 Luis F. Ortiz            Carl Osterwisch
Ortega-Clavero
Janne Olavi Paanajärvi   Scott Pakin              José Luis García
                                                  Pallero
Jason Alan Palmer        Gabriele Pannocchia      Sylvain Pelissier
Rolando Pereira          Per Persson              Primozz Peterlin
Jim Peterson             Danilo Piazzalunga       Nicholas Piper
Elias Pipping            Robert Platt             Hans Ekkehard Plesser
Sergey Plotnikov         Tom Poage                Nathan Podlich
Orion Poplawski          Ondrej Popp              Jef Poskanzer
Francesco Potortì        Konstantinos Poulios     Tejaswi D. Prakash
Jarno Rajahalme          Eduardo Ramos            Pooja Rao
James B. Rawlings        Eric S. Raymond          Balint Reczey
Joshua Redstone          Andy Register            Lukas Reichlin
Michael Reifenberger     Ernst Reissner           Jens Restemeier
Anthony Richardson       Jason Riedy              E. Joshua Rigler
Sander van Rijn          Petter Risholm           Matthew W. Roberts
Melvin Robinson          Dmitry Roshchin          Peter Rosin
Andrew Ross              Fabio Rossi              Mark van Rossum
Joe Rothweiler           David Rörich             Kevin Ruland
Kristian Rumberg         Ryan Rusaw               Olli Saarela
Toni Saarela             Juhani Saastamoinen      Radek Salac
Mike Sander              Ben Sapp                 Aleksej Saushev
Alois Schlögl            Michel D. Schmid         Julian Schnidder
Sebastian Schöps         Nicol N. Schraudolph     Sebastian Schubert
Lasse Schuirmann         Ludwig Schwardt          Thomas L. Scofield
Daniel J. Sebald         Dmitri A. Sergatskov     Vanya Sergeev
Marko Seric              Ahsan Ali Shahid         Baylis Shanks
Andriy Shinkarchuck      Robert T. Short          Joseph P. Skudlarek
John Smith               Julius Smith             Shan G. Smith
Peter L. Sondergaard     Rüdiger Sonderfeld       Joerg Specht
Quentin H. Spencer       Christoph Spiel          David Spies
Andreas Stahel           Richard Stallman         Russell Standish
Ryan Starret             Brett Stewart            Doug Stewart
Jen Stewart              Jonathan Stickel         Judd Storrs
Thomas Stuart            Bernardo Sulzbach        Ivan Sutoris
John Swensen             Daisuke Takago           Ariel Tankus
Falk Tannhäuser          Duncan Temple Lang       Matthew Tenny
Kris Thielemans          Georg Thimm              Corey Thomasson
Andrew Thornton          Olaf Till                Christophe Tournery
Thomas Treichl           Abhinav Tripathi         Karsten Trulsen
David Turner             Frederick Umminger       Utkarsh Upadhyay
José Vallet              Stefan van der Walt      Peter Van Wieren
James R. Van Zandt       Risto Vanhanen           Gregory Vanuxem
Mihas Varantsou          Ivana Varekova           Sébastien Villemot
Marco Vitetta            Daniel Wagenaar          Thomas Walter
Andreas Weber            Olaf Weber               Thomas Weber
Rik Wehbring             Bob Weigel               Andreas Weingessel
Martin Weiser            Michael Weitzel          David Wells
Joachim Wiesemann        Alexander Wilms          Joe Winegarden
Georg Wiora              Sahil Yadav              Fook Fah Yap
Sean Young               Michele Zaffalon         Serhiy Zahoriya
Johannes Zarl            Michael Zeising          Federico Zenith
Claudius Zingerli        Alex Zvoleff             Richard Zweig

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

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

 -- : citation
 -- : 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.  See
<https://www.octave.org/get-involved.html> for detailed information.

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

   The current version of Octave executes in a graphical user interface
(GUI). The GUI hosts an Integrated Development Environment (IDE) which
includes a code editor with syntax highlighting, built-in debugger,
documentation browser, as well as the interpreter for the language
itself.  A command-line interface for Octave is also available.

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

* 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 starts the graphical user interface.  The central window in the GUI
is the Octave command-line interface.  In this window 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 then
only the command prompt appears in the same window that was running a
shell.  In either 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, we 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 uses standard mathematical notation with the advantage over
low-level languages that operators may act on scalars, vector, matrices,
or N-dimensional arrays.  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)

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 -dpdf foo.pdf

will create a file called ‘foo.pdf’ that contains a rendering of the
current plot in Portable Document Format.  The command

     help print

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

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

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

   In order to get good help you first need to know the name of the
command that you want to use.  The name of this 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
(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.

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

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


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

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

This section explains the notation 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: <RET>.


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.  If there are multiple ways to invoke the
function then each allowable form is listed.

   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.

   After all of the calling forms have been enumerated, the next line is
a concise one-sentence summary of the function.

   After the summary there may be documentation on the inputs and
outputs, examples of function usage, notes about the algorithm used, and
references to related functions.

   Here is a description of an imaginary function ‘foo’:

 -- : foo (X)
 -- : foo (X, Y)
 -- : foo (X, Y, ...)
     Subtract X from Y, then add any remaining arguments to the result.

     The input X must be a numeric scalar, vector, or array.

     The optional input Y defaults to 19 if it is not supplied.

     Example:

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

     More generally,

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

     See also: bar

   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.


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

Commands are functions that may be called without surrounding their
arguments in parentheses.  Command descriptions have a format similar to
function descriptions.  For example, here is the description for
Octave’s ‘diary’ command:

 -- : diary
 -- : diary on
 -- : diary off
 -- : diary FILENAME
 -- : [STATUS, DIARYFILE] = diary
     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 input or output arguments, ‘diary’ toggles the current
     diary state.

     If output arguments are requested, ‘diary’ ignores inputs and
     returns the current status.  The boolean STATUS indicates whether
     recording is on or off, and DIARYFILE is the name of the file where
     the session is stored.

     See also: history, evalc.


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

‘--gui’
     Start the graphical user interface (GUI).

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

‘--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.  This is the default behavior, but this
     option may be useful to override a previous ‘--gui’.

‘--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                             = ""
          beep_on_error                   = true
          confirm_recursive_rmdir         = false
          crash_dumps_octave_core         = false
          disable_diagonal_matrix         = true
          disable_permutation_matrix      = true
          disable_range                   = true
          fixed_point_format              = true
          history_timestamp_format_string = "%%-- %D %I:%M %p --%%"
          print_empty_dimensions          = false
          save_default_options            = "-mat-binary"
          struct_levels_to_print          = 0

     and disable the following warnings

          Octave:abbreviated-property-match
          Octave:data-file-in-path
          Octave:function-name-clash
          Octave:possible-matlab-short-circuit-operator

     Note that this does not enable the ‘Octave:language-extension’
     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.

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

 -- : program_name ()
     Return the last component of the value returned by
     ‘program_invocation_name’.

     See also: *note program_invocation_name:
     XREFprogram_invocation_name.

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

‘startup.m’
     This file is used to make personal changes to the default Octave
     environment.  It is executed for MATLAB compatibility, but
     ‘~/.octaverc’ is the preferred location for configuration changes.

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


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

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

Shutdown is initiated with the ‘exit’ or ‘quit’ commands (they are
equivalent).  Similar to startup, Octave has a shutdown process that can
be customized by user script files.  During shutdown Octave will search
for the script file ‘finish.m’ in the function load path.  Commands to
save all workspace variables or cleanup temporary files may be placed
there.  Additional functions to execute on shutdown may be registered
with ‘atexit’.

 -- : exit
 -- : exit (STATUS)
 -- : quit
 -- : quit (STATUS)
     Exit the current Octave session.

     If the optional integer value STATUS is supplied, pass that value
     to the operating system as Octave’s exit status.  The default value
     is zero.

     When exiting, Octave will attempt to run the m-file ‘finish.m’ if
     it exists.  User commands to save the workspace or clean up
     temporary files may be placed in that file.  Alternatively, another
     m-file may be scheduled to run using ‘atexit’.

     See also: *note atexit: XREFatexit.

 -- : atexit (FCN)
 -- : 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.

     See also: *note quit: XREFquit.


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.

 -- : help NAME
 -- : help --list
 -- : help .
 -- : 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’ displays instructions on
     how to access help from the command line.

     The help command can provide information about most operators, but
     NAME must be enclosed by single or double quotes to prevent the
     Octave interpreter from acting on NAME.  For example, ‘help "+"’
     displays help on the addition operator.

     See also: *note doc: XREFdoc, *note lookfor: XREFlookfor, *note
     which: XREFwhich, *note info: XREFinfo.

 -- : doc FUNCTION_NAME
 -- : doc
     Display documentation for the function FUNCTION_NAME directly from
     an online version of the printed manual, using the GNU Info
     browser.

     If invoked without an argument, 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.

 -- : lookfor STR
 -- : lookfor -all STR
 -- : [FCN, HELP1STR] = lookfor (STR)
 -- : [FCN, HELP1STR] = lookfor ("-all", STR)
     Search for the string STR in the documentation of all functions in
     the current function search path.

     By default, ‘lookfor’ looks for STR in just the first sentence of
     the help string for each function found.  The entire help text of
     each function can be searched by using the "-all" argument.  All
     searches are case insensitive.

     When called with no output arguments, ‘lookfor’ prints the list of
     matching functions to the terminal.  Otherwise, the output argument
     FCNS contains the function names and HELP1STR contains the first
     sentence from the help string of each function.

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

     The speed of lookup is greatly enhanced by having a cached
     documentation file.  See ‘doc_cache_create’ for more information.

     See also: *note help: XREFhelp, *note doc: XREFdoc, *note which:
     XREFwhich, *note path: XREFpath, *note doc_cache_create:
     XREFdoc_cache_create.

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

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

     See also: *note ver: XREFver, *note pkg: XREFpkg.

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

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

 -- : VAL = info_file ()
 -- : OLD_VAL = info_file (NEW_VAL)
 -- : 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.

 -- : VAL = info_program ()
 -- : OLD_VAL = info_program (NEW_VAL)
 -- : 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.

 -- : VAL = makeinfo_program ()
 -- : OLD_VAL = makeinfo_program (NEW_VAL)
 -- : 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.

 -- : VAL = texi_macros_file ()
 -- : OLD_VAL = texi_macros_file (NEW_VAL)
 -- : 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.

 -- : VAL = doc_cache_file ()
 -- : OLD_VAL = doc_cache_file (NEW_VAL)
 -- : 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.

     See also: *note lookfor: XREFlookfor.

 -- : VAL = built_in_docstrings_file ()
 -- : OLD_VAL = built_in_docstrings_file (NEW_VAL)
 -- : 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.

 -- : VAL = suppress_verbose_help_message ()
 -- : OLD_VAL = suppress_verbose_help_message (NEW_VAL)
 -- : 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.

 -- : doc_cache_create (OUT_FILE, DIRECTORY)
 -- : doc_cache_create (OUT_FILE)
 -- : doc_cache_create ()
     Generate documentation cache for all functions in DIRECTORY.

     A documentation cache is generated for all functions in DIRECTORY
     which may be a single string or a cell array of strings.  The cache
     is used to speed up the function ‘lookfor’.

     The cache is saved in the file OUT_FILE which defaults to the value
     ‘doc-cache’ if not given.

     If no directory is given (or it is the empty matrix), a cache for
     built-in functions, operators, and keywords is generated.

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

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

     See also: *note get_help_text_from_file:
     XREFget_help_text_from_file.

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

     See also: *note get_help_text: XREFget_help_text.

 -- : TEXT = get_first_help_sentence (NAME)
 -- : TEXT = get_first_help_sentence (NAME, MAX_LEN)
 -- : [TEXT, STATUS] = get_first_help_sentence (...)
     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 nonzero, 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.

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

 -- : VAL = completion_append_char ()
 -- : OLD_VAL = completion_append_char (NEW_VAL)
 -- : 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.

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

 -- : history
 -- : history OPT1 ...
 -- : H = history ()
 -- : 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.

     See also: *note edit_history: XREFedit_history, *note run_history:
     XREFrun_history.

 -- : edit_history
 -- : edit_history CMD_NUMBER
 -- : 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, *note history:
     XREFhistory.

 -- : run_history
 -- : run_history CMD_NUMBER
 -- : 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, *note history:
     XREFhistory.

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

 -- : VAL = history_save ()
 -- : OLD_VAL = history_save (NEW_VAL)
 -- : 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.

 -- : VAL = history_control ()
 -- : 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.

 -- : VAL = history_file ()
 -- : 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.

 -- : VAL = history_size ()
 -- : 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.

 -- : VAL = history_timestamp_format_string ()
 -- : OLD_VAL = history_timestamp_format_string (NEW_VAL)
 -- : 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.

 -- : VAL = EDITOR ()
 -- : OLD_VAL = EDITOR (NEW_VAL)
 -- : 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.

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

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

 -- : VAL = PS1 ()
 -- : OLD_VAL = PS1 (NEW_VAL)
 -- : 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.

 -- : VAL = PS2 ()
 -- : OLD_VAL = PS2 (NEW_VAL)
 -- : 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.

 -- : VAL = PS4 ()
 -- : OLD_VAL = PS4 (NEW_VAL)
 -- : 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 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.

 -- : diary
 -- : diary on
 -- : diary off
 -- : diary FILENAME
 -- : [STATUS, DIARYFILE] = diary
     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 input or output arguments, ‘diary’ toggles the current
     diary state.

     If output arguments are requested, ‘diary’ ignores inputs and
     returns the current status.  The boolean STATUS indicates whether
     recording is on or off, and DIARYFILE is the name of the file where
     the session is stored.

     See also: *note history: XREFhistory, *note evalc: XREFevalc.

   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.

 -- : echo
 -- : echo on
 -- : echo off
 -- : echo on all
 -- : echo off all
 -- : echo FUNCTION on
 -- : echo FUNCTION off
     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.

     ‘FUNCTION on’
          Enable echoing of commands as they are executed in the named
          function.

     ‘FUNCTION off’
          Disable echoing of commands as they are executed in the named
          function.

     With no arguments, ‘echo’ toggles the current echo state.

     See also: *note PS4: XREFPS4.


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

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

 -- : CLASSNAME = class (OBJ)
 -- : class (S, ID)
 -- : 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.

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

     If CLASSNAME is a cell array of string, a logical array of the same
     size is returned, containing true for each class to which OBJ
     belongs to.

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

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

     Both VAL and TYPE are typically one of the following built-in
     classes:

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

     The value VAL may be modified to fit within the range of the new
     type.

     Examples:

          cast (-5, "uint8")
             ⇒ 0
          cast (300, "int8")
             ⇒ 127

     Programming Note: This function relies on the object VAL having a
     conversion method named TYPE.  User-defined classes may implement
     only a subset of the full list of types shown above.  In that case,
     it may be necessary to call cast twice in order to reach the
     desired type.  For example, the conversion to double is nearly
     always implemented, but the conversion to uint8 might not be.  In
     that case, the following code will work

          cast (cast (USER_DEFINED_VAL, "double"), "uint8")

     See also: *note typecast: XREFtypecast, *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,
     *note single: XREFsingle, *note logical: XREFlogical, *note char:
     XREFchar, *note class: XREFclass, *note typeinfo: XREFtypeinfo.

 -- : Y = 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 only used with 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 will 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 bitpack: XREFbitpack, *note
     bitunpack: XREFbitunpack, *note swapbytes: XREFswapbytes.

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

 -- : Y = bitpack (X, CLASS)
     Return a new array Y resulting from interpreting the logical array
     X as raw bit patterns for data of the numeric class CLASS.

     CLASS must be one of the built-in numeric classes:

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

     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.

 -- : Y = bitunpack (X)
     Return a logical array Y corresponding to the raw bit patterns of
     X.

     X must belong to one of the built-in numeric classes:

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

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

 -- : NA
 -- : NA (N)
 -- : NA (N, M)
 -- : NA (N, M, K, ...)
 -- : 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.

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

 -- : ndims (A)
     Return the number of dimensions of A.

     For any array, the result will always be greater than or equal to
     2.  Trailing singleton dimensions are not counted.

          ndims (ones (4, 1, 2, 1))
              ⇒ 3

     See also: *note size: XREFsize.

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

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

 -- : numel (A)
 -- : 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 scalar numbers.  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.  Or
     the index could be the string ":" which represents the colon
     operator.  For example,

          A = ones (5, 3);
          numel (A, 2, ":")

     will return 3 as the second row has three column entries.

     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, *note length: XREFlength, *note
     ndims: XREFndims.

 -- : 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 or N-dimensional objects, the
     length is the number of elements along the largest dimension
     (equivalent to ‘max (size (A))’).

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

 -- : SZ = size (A)
 -- : DIM_SZ = size (A, DIM)
 -- : [ROWS, COLS, ..., DIM_N_SZ] = size (...)
     Return a row vector with the size (number of elements) of each
     dimension for the object A.

     When given a second argument, DIM, return the size of the
     corresponding dimension.

     With a single output argument, ‘size’ returns a row vector.  When
     called with multiple output arguments, ‘size’ returns the size of
     dimension N in the Nth argument.  The number of rows, dimension 1,
     is returned in the first argument, the number of columns, dimension
     2, is returned in the second argument, etc.  If there are more
     dimensions in A then there are output arguments, ‘size’ returns the
     total number of elements in the remaining dimensions in the final
     output argument.

     Example 1: single row vector output

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

     Example 2: number of elements in 2nd dimension (columns)

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

     Example 3: number of output arguments == number of dimensions

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

     Example 4: number of output arguments != number of dimensions

          [nr, remainder] = size (ones (2, 3, 4, 5))
              ⇒ nr = 2
              ⇒ remainder = 60

     See also: *note numel: XREFnumel, *note ndims: XREFndims, *note
     length: XREFlength, *note rows: XREFrows, *note columns:
     XREFcolumns, *note size_equal: XREFsize_equal, *note common_size:
     XREFcommon_size.

 -- : isempty (A)
     Return true if A is an empty matrix (any one of its dimensions is
     zero).

     See also: *note isnull: XREFisnull, *note isa: XREFisa.

 -- : isnull (X)
     Return true if X is a special null matrix, string, or single quoted
     string.

     Indexed assignment with such a null value on the right-hand side
     should delete array elements.  This function is used in place of
     ‘isempty’ when overloading the indexed assignment method
     (‘subsasgn’) for user-defined classes.  ‘isnull’ is used to
     distinguish between these two cases:

     ‘A(I) = []’

     and

     ‘X = []; A(I) = X’

     In the first assignment, the right-hand side is ‘[]’ which is a
     special null value.  As long as the index I is not empty, this code
     should delete elements from A rather than perform assignment.

     In the second assignment, the right-hand side is empty (because X
     is ‘[]’), but it is *not* null.  This code should assign the empty
     value to elements in A.

     An example from Octave’s built-in char class demonstrates the
     interpreter behavior when ‘isnull’ is used correctly.

          str = "Hello World";
          nm = "Wally";
          str(7:end) = nm                # indexed assignment
            ⇒ str = Hello Wally
          str(7:end) = ""                # indexed deletion
            ⇒ str = Hello

     See also: *note isempty: XREFisempty, *note isindex: XREFisindex.

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

     See also: *note whos: XREFwhos.

 -- : size_equal (A, B, ...)
     Return true if the dimensions of all arguments agree.

     Trailing singleton dimensions are ignored.  When called with a
     single argument, or no argument, ‘size_equal’ returns true.

     See also: *note size: XREFsize, *note numel: XREFnumel, *note
     ndims: XREFndims, *note common_size: XREFcommon_size.

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

   If the numeric constant is a real integer, it can be defined in
decimal, hexadecimal, or binary notation.  Hexadecimal notation starts
with ‘0x’ or ‘0X’, binary notation starts with ‘0b’ or ‘0B’, otherwise
decimal notation is assumed.  As a consequence, ‘0b’ is not a
hexadecimal number, in fact, it is not a valid number at all.

   For better readability, digits may be partitioned by the underscore
separator ‘_’, which is ignored by the Octave interpreter.  Here are
some examples of real-valued integer constants, which all represent the
same value and are internally stored as binary64:

     42            # decimal notation
     0x2A          # hexadecimal notation
     0b101010      # binary notation
     0b10_1010     # underscore notation
     round (42.1)  # also binary64

   In decimal notation, the numeric constant may be denoted as decimal
fraction or even in scientific (exponential) notation.  Note that this
is not possible for hexadecimal or binary notation.  Again, in the
following example all numeric constants represent the same value:

     .105
     1.05e-1
     .00105e+2

   Unlike most programming languages, complex numeric constants are
denoted as the sum of real and imaginary parts.  The imaginary part is
denoted by a real-valued numeric constant followed immediately by a
complex value indicator (‘i’, ‘j’, ‘I’, or ‘J’ which represents ‘sqrt
(-1)’).  No spaces are allowed between the numeric constant and the
complex value indicator.  Some examples of complex numeric constants
that all represent the same value:

     3 + 42i
     3 + 42j
     3 + 42I
     3 + 42J
     3.0 + 42.0i
     3.0 + 0x2Ai
     3.0 + 0b10_1010i
     0.3e1 + 420e-1i

 -- : double (X)
     Convert X to double precision type.

     See also: *note single: XREFsingle.

 -- : complex (X)
 -- : complex (RE, IM)
     Return a complex value from real arguments.

     With 1 real argument X, return the complex result ‘X + 0i’.

     With 2 real arguments, return the complex result ‘RE + IMi’.
     ‘complex’ can often be more convenient than expressions such as
     ‘a + b*i’.  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.

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

 -- : output_max_field_width
     This function is obsolete and will be removed from a future version
     of Octave.

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

     Note that regardless of the value set for ‘output_precision’, the
     number of digits of precision displayed is limited to 16 for double
     precision values and 7 for single precision values.

     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.

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

 -- : VAL = split_long_rows ()
 -- : OLD_VAL = split_long_rows (NEW_VAL)
 -- : 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.

 -- : VAL = fixed_point_format ()
 -- : OLD_VAL = fixed_point_format (NEW_VAL)
 -- : 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 possibility 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_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.

 -- : VAL = print_empty_dimensions ()
 -- : OLD_VAL = print_empty_dimensions (NEW_VAL)
 -- : 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_
normally 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.

   This space saving optimization may be disabled using the function
“disable_range”.

 -- : VAL = disable_range ()
 -- : OLD_VAL = disable_range (NEW_VAL)
 -- : disable_range (NEW_VAL, "local")
     Query or set the internal variable that controls whether ranges are
     stored in a special space-efficient format.

     The default value is true.  If this option is disabled Octave will
     store ranges as full matrices.

     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 disable_diagonal_matrix:
     XREFdisable_diagonal_matrix, *note disable_permutation_matrix:
     XREFdisable_permutation_matrix.

   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.

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

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

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

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

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

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

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

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

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

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

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

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

 -- : flintmax ()
 -- : flintmax ("double")
 -- : 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 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’.

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

 -- : C = bitset (A, N)
 -- : C = bitset (A, N, VAL)
     Set or reset bit(s) N of the unsigned integers in A.

     VAL = 0 resets and VAL = 1 sets the bits.  The least 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 intmax: XREFintmax,
     *note flintmax: XREFflintmax.

 -- : C = bitget (A, N)
     Return the status of bit(s) N of the unsigned integers in A.

     The least 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 intmax: XREFintmax,
     *note flintmax: XREFflintmax.

   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
two utility functions: ‘flintmax’ for floating point integers, and
‘intmax’ for integer objects (‘uint8’, ‘int64’, etc.).

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

 -- : bitand (X, Y)
     Return the bitwise AND of non-negative integers.

     X, Y must be in the range [0,intmax]

     See also: *note bitor: XREFbitor, *note bitxor: XREFbitxor, *note
     bitset: XREFbitset, *note bitget: XREFbitget, *note bitcmp:
     XREFbitcmp, *note bitshift: XREFbitshift, *note intmax: XREFintmax,
     *note flintmax: XREFflintmax.

 -- : bitor (X, Y)
     Return the bitwise OR of non-negative integers X and Y.

     See also: *note bitor: XREFbitor, *note bitxor: XREFbitxor, *note
     bitset: XREFbitset, *note bitget: XREFbitget, *note bitcmp:
     XREFbitcmp, *note bitshift: XREFbitshift, *note intmax: XREFintmax,
     *note flintmax: XREFflintmax.

 -- : bitxor (X, Y)
     Return the bitwise XOR of non-negative integers X and Y.

     See also: *note bitand: XREFbitand, *note bitor: XREFbitor, *note
     bitset: XREFbitset, *note bitget: XREFbitget, *note bitcmp:
     XREFbitcmp, *note bitshift: XREFbitshift, *note intmax: XREFintmax,
     *note flintmax: XREFflintmax.

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

 -- : bitcmp (A, K)
     Return the K-bit complement of integers in A.

     If K is omitted ‘k = log2 (flintmax) + 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 flintmax: XREFflintmax.

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

 -- : bitshift (A, K)
 -- : 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 64.  N must be in the range [1,64].

          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 intmax: XREFintmax,
     *note flintmax: XREFflintmax.

   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.

 -- : logical (X)
     Convert the numeric object X to logical type.

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

 -- : true (X)
 -- : true (N, M)
 -- : 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.

 -- : false (X)
 -- : false (N, M)
 -- : 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.

 -- : 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 ischar: XREFischar, *note islogical:
     XREFislogical, *note isstring: XREFisstring, *note iscell:
     XREFiscell, *note isstruct: XREFisstruct, *note isa: XREFisa.

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

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

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

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

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

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

 -- : ismatrix (A)
     Return true if A is a 2-D array.

     See also: *note isscalar: XREFisscalar, *note isvector:
     XREFisvector, *note iscell: XREFiscell, *note isstruct:
     XREFisstruct, *note issparse: XREFissparse, *note isa: XREFisa.

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

 -- : isrow (X)
     Return true if X is a row vector 1xN with non-negative N.

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

 -- : iscolumn (X)
     Return true if X is a column vector Nx1 with non-negative N.

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

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

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

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

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

 -- : issymmetric (A)
 -- : issymmetric (A, TOL)
     Return true if A is a symmetric matrix within the tolerance
     specified by TOL.

     The default tolerance is zero (uses faster code).

     Matrix A is considered symmetric if ‘norm (A - A.', Inf) / norm (A,
     Inf) < TOL’.

     See also: *note ishermitian: XREFishermitian, *note isdefinite:
     XREFisdefinite.

 -- : ishermitian (A)
 -- : ishermitian (A, TOL)
     Return true if A is Hermitian within the tolerance specified by
     TOL.

     The default tolerance is zero (uses faster code).

     Matrix A is considered symmetric if ‘norm (A - A', Inf) / norm (A,
     Inf) < TOL’.

     See also: *note issymmetric: XREFissymmetric, *note isdefinite:
     XREFisdefinite.

 -- : isdefinite (A)
 -- : isdefinite (A, TOL)
     Return 1 if A is symmetric positive definite within the tolerance
     specified by TOL or 0 if A is symmetric positive semi-definite.
     Otherwise, return -1.

     If TOL is omitted, use a tolerance of ‘100 * eps * norm (A, "fro")’

     See also: *note issymmetric: XREFissymmetric, *note ishermitian:
     XREFishermitian.

 -- : isbanded (A, LOWER, UPPER)
     Return true if A is a matrix with entries confined between LOWER
     diagonals below the main diagonal and UPPER diagonals above the
     main diagonal.

     LOWER and UPPER must be non-negative integers.

     See also: *note isdiag: XREFisdiag, *note istril: XREFistril, *note
     istriu: XREFistriu, *note bandwidth: XREFbandwidth.

 -- : isdiag (A)
     Return true if A is a diagonal matrix.

     See also: *note isbanded: XREFisbanded, *note istril: XREFistril,
     *note istriu: XREFistriu, *note diag: XREFdiag, *note bandwidth:
     XREFbandwidth.

 -- : istril (A)
     Return true if A is a lower triangular matrix.

     A lower triangular matrix has nonzero entries only on the main
     diagonal and below.

     See also: *note istriu: XREFistriu, *note isbanded: XREFisbanded,
     *note isdiag: XREFisdiag, *note tril: XREFtril, *note bandwidth:
     XREFbandwidth.

 -- : istriu (A)
     Return true if A is an upper triangular matrix.

     An upper triangular matrix has nonzero entries only on the main
     diagonal and above.

     See also: *note isdiag: XREFisdiag, *note isbanded: XREFisbanded,
     *note istril: XREFistril, *note triu: XREFtriu, *note bandwidth:
     XREFbandwidth.

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

     A prime number is conventionally defined as a positive integer
     greater than 1 (e.g., 2, 3, ...) which is divisible only by itself
     and 1.  Octave extends this definition to include both negative
     integers and complex values.  A negative integer is prime if its
     positive counterpart is prime.  This is equivalent to ‘isprime (abs
     (x))’.

     If ‘class (X)’ is complex, then primality is tested in the domain
     of Gaussian integers
     (<https://en.wikipedia.org/wiki/Gaussian_integer>).  Some
     non-complex integers are prime in the ordinary sense, but not in
     the domain of Gaussian integers.  For example, 5 = (1+2i)*(1-2i)
     shows that 5 is not prime because it has a factor other than itself
     and 1.  Exercise caution when testing complex and real values
     together in the same matrix.

     Examples:

          isprime (1:6)
              ⇒ [0, 1, 1, 0, 1, 0]

          isprime ([i, 2, 3, 5])
              ⇒ [0, 0, 1, 0]

     Programming Note: ‘isprime’ is appropriate if the maximum value in
     X is not too large (< 1e15).  For larger values special purpose
     factorization code should be used.

     Compatibility Note: MATLAB does not extend the definition of prime
     numbers and will produce an error if given negative or complex
     inputs.

     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:

     double ("\n")
         ⇒ 10
     double ('\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’.

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

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

 -- : 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 isstring: XREFisstring, *note iscellstr:
     XREFiscellstr, *note isa: XREFisa.

 -- : isstring (S)
     Return true if S is a string array.

     A string array is a data type that stores strings (row vectors of
     characters) at each element in the array.  It is distinct from
     character arrays which are N-dimensional arrays where each element
     is a single 1x1 character.  It is also distinct from cell arrays of
     strings which store strings at each element, but use cell indexing
     ‘{}’ to access elements rather than string arrays which use
     ordinary array indexing ‘()’.

     Programming Note: Octave does not yet implement string arrays so
     this function will always return false.

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

   To test if an object is a string (i.e., a 1xN row vector of
characters and not a character matrix) you can use the ‘ischar’ function
in combination with the ‘isrow’ function as in the following example:

     ischar (collection)
          ⇒ 1

     ischar (collection) && isrow (collection)
          ⇒ 0

     ischar ("my string") && isrow ("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.

 -- : VAL = string_fill_char ()
 -- : OLD_VAL = string_fill_char (NEW_VAL)
 -- : 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.

     The value must be a single character and the default 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).

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

 -- : char (X)
 -- : char (X, ...)
 -- : char (S1, S2, ...)
 -- : 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.

 -- : strvcat (X)
 -- : strvcat (X, ...)
 -- : strvcat (S1, S2, ...)
 -- : 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.

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

 -- : cstrcat (S1, S2, ...)
     Return a string containing all the arguments concatenated
     horizontally with trailing white space 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.).

 -- : S = mat2str (X, N)
 -- : 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.

 -- : num2str (X)
 -- : num2str (X, PRECISION)
 -- : 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 process 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"

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

     Programming Notes:

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

     Integers larger than ‘flintmax’ may not be displayed correctly.

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

     Any optional FORMAT specified by the programmer is used without
     modification.  This is in contrast to MATLAB which tampers with the
     FORMAT based on internal heuristics.

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

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

     Programming Notes:

     Non-integers are rounded to integers before display.  Only the real
     part of complex numbers is displayed.

     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.

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

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

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

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


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.

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

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

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

 -- : findstr (S, T)
 -- : 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 (default), the returned
     vector can include overlapping positions.  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.

 -- : IDX = strchr (STR, CHARS)
 -- : IDX = strchr (STR, CHARS, N)
 -- : IDX = strchr (STR, CHARS, N, DIRECTION)
 -- : [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.

 -- : index (S, T)
 -- : 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.

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

 -- : IDX = strfind (STR, PATTERN)
 -- : IDX = strfind (CELLSTR, PATTERN)
 -- : 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,
     or if PATTERN itself is empty, 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.

 -- : STR = strjoin (CSTR)
 -- : 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 are 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: *note strsplit: XREFstrsplit.

 -- : strmatch (S, A)
 -- : 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.

 -- : [TOK, REM] = strtok (STR)
 -- : [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.

     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.

     Leading delimiters are ignored.  If DELIM is not specified,
     whitespace is assumed.

     If REM is requested, it contains the remainder of the string,
     starting at the first delimiter.

     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.

 -- : [CSTR] = strsplit (STR)
 -- : [CSTR] = strsplit (STR, DEL)
 -- : [CSTR] = strsplit (..., NAME, VALUE)
 -- : [CSTR, MATCHES] = strsplit (...)
     Split the string STR using the delimiters specified by DEL and
     return a cell string array of substrings.

     If a delimiter is not specified the string is split at whitespace
     ‘{" ", "\f", "\n", "\r", "\t", "\v"}’.  Otherwise, the delimiter,
     DEL must be a string or cell array of strings.  By default,
     consecutive delimiters in the input string S are collapsed into one
     resulting in a single split.

     Supported NAME/VALUE pair arguments are:

        • COLLAPSEDELIMITERS which may take the value of ‘true’
          (default) or ‘false’.

        • DELIMITERTYPE which may take the value of "simple" (default)
          or "regularexpression".  A simple delimiter matches the text
          exactly as written.  Otherwise, the syntax for regular
          expressions outlined in ‘regexp’ is used.

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

     Examples with simple delimiters:

          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", {" ", ",", "foo", "bar"})
                ⇒
                    {
                      [1,1] = a
                      [1,2] = b
                      [1,3] = c
                    }

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


     Examples with regularexpression delimiters:

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

          strsplit ("a,,b, c", '[, ]', "collapsedelimiters", 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.

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

 -- : [A, ...] = strread (STR)
 -- : [A, ...] = strread (STR, FORMAT)
 -- : [A, ...] = strread (STR, FORMAT, FORMAT_REPEAT)
 -- : [A, ...] = strread (STR, FORMAT, PROP1, VALUE1, ...)
 -- : [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).  Note that whitespace is
          implicitly added to the set of delimiter characters unless a
          "%s" format conversion specifier is supplied; see "whitespace"
          parameter below.  The set of delimiter characters cannot be
          empty; if needed Octave substitutes a space as delimiter.

     "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".  In each data field, multiple consecutive whitespace
          characters are collapsed into one space and leading and
          trailing whitespace is removed.  The default value for
          whitespace is " \b\r\n\t" (note the space).  Whitespace is
          always added to the set of delimiter characters unless at
          least one "%s" format conversion specifier is supplied; in
          that case only whitespace explicitly specified in "delimiter"
          is retained as delimiter and removed from the set of
          whitespace characters.  If whitespace characters are to be
          kept as-is (in e.g., strings), specify an empty value (i.e.,
          "") for "whitespace"; obviously, whitespace cannot be a
          delimiter then.

     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.

 -- : NEWSTR = strrep (STR, PTN, REP)
 -- : NEWSTR = strrep (CELLSTR, PTN, REP)
 -- : 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.

 -- : NEWSTR = erase (STR, PTN)
     Delete all occurrences of PTN within STR.

     STR and PTN can be ordinary strings, cell array of strings, or
     character arrays.

     Examples

          ## string, single pattern
          erase ("Hello World!", " World")
              ⇒ "Hello!"

          ## cellstr, single pattern
          erase ({"Hello", "World!"}, "World")
              ⇒ {"Hello", "!"}

          ## string, multiple patterns
          erase ("The Octave interpreter is fabulous", {"interpreter ", "The "})
              ⇒ "Octave is fabulous"

          ## cellstr, multiple patterns
          erase ({"The ", "Octave interpreter ", "is fabulous"}, {"interpreter ", "The "})
              ⇒ {"", "Octave ", "is fabulous"}

     Programming Note: ‘erase’ deletes the first instance of a pattern
     in a string when there are overlapping occurrences.  For example:

          erase ("abababa", "aba")
              ⇒ "b"

     See ‘strrep’ for processing overlaps.

     See also: *note strrep: XREFstrrep, *note regexprep: XREFregexprep.

 -- : substr (S, OFFSET)
 -- : 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.

 -- : [S, E, TE, M, T, NM, SP] = regexp (STR, PAT)
 -- : [...] = 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, escape
     sequences in PAT (e.g., "\n" => newline) are expanded even when PAT
     has been defined with single quotes.  To disable expansion use a
     second backslash before 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.

     Stack Limitation Note: Pattern searches are done with a recursive
     function which can overflow the program stack when there are a high
     number of matches.  For example,

          regexp (repmat ('a', 1, 1e5), '(a)+')

     may lead to a segfault.  As an alternative, consider constructing
     pattern searches that reduce the number of matches (e.g., by
     creatively using set complement), and then further processing the
     return variables (now reduced in size) with successive ‘regexp’
     searches.

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

 -- : [S, E, TE, M, T, NM, SP] = regexpi (STR, PAT)
 -- : [...] = 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.

 -- : OUTSTR = regexprep (STRING, PAT, REPSTR)
 -- : 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, escape
     sequences in PAT (e.g., "\n" => newline) are expanded even when PAT
     has been defined with single quotes.  To disable expansion use a
     second backslash before the escape sequence (e.g., "\\n") or use
     the ‘regexptranslate’ function.

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

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

 -- : untabify (T)
 -- : untabify (T, TW)
 -- : untabify (T, TW, DEBLANK)
     Replace TAB characters in T with spaces.

     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.

     The tab width is specified by TW, and defaults to eight.

     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

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

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

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

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

 -- : dec2base (D, BASE)
 -- : 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.

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

 -- : S = num2hex (N)
 -- : S = num2hex (N, "cell")
     Convert a numeric array to an array of hexadecimal strings.

     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"

     With the optional second argument "cell, return a cell array of
     strings instead of a character array.

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

 -- : N = hex2num (S)
 -- : N = hex2num (S, CLASS)
     Typecast a hexadecimal character array or cell array of strings to
     an array of numbers.

     By default, the input array is interpreted as a hexadecimal number
     representing a double precision value.  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 second argument CLASS may be used to cause the input
     array to be interpreted as a different value type.  Possible values
     are

     Option   Characters
     ----------------------
     "int8"   2
     "uint8"  2
     "int16"  4
     "uint16" 4
     "int32"  8
     "uint32" 8
     "int64"  16
     "uint64" 16
     "char"   2
     "single" 8
     "double" 16

     For example:

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

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

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

 -- : strjust (S)
 -- : 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.

 -- : X = str2num (S)
 -- : [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.

 -- : tolower (S)
 -- : 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.

 -- : toupper (S)
 -- : 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.

 -- : NATIVE_BYTES = unicode2native (UTF8_STR, CODEPAGE)
 -- : NATIVE_BYTES = unicode2native (UTF8_STR)
     Convert UTF-8 string UTF8_STR to byte stream using CODEPAGE.

     The character vector UTF8_STR is converted to a byte stream
     NATIVE_BYTES using the code page given by CODEPAGE.  The string
     CODEPAGE must be an identifier of a valid code page.  Examples for
     valid code pages are "ISO-8859-1", "Shift-JIS", or "UTF-16".  For a
     list of supported code pages, see
     <https://www.gnu.org/software/libiconv>.  If CODEPAGE is omitted or
     empty, the system default codepage is used.

     If any of the characters cannot be mapped into the codepage
     CODEPAGE, they are replaced with the appropriate substitution
     sequence for that codepage.

     See also: *note native2unicode: XREFnative2unicode.

 -- : UTF8_STR = native2unicode (NATIVE_BYTES, CODEPAGE)
 -- : UTF8_STR = native2unicode (NATIVE_BYTES)
     Convert byte stream NATIVE_BYTES to UTF-8 using CODEPAGE.

     The numbers in the vector NATIVE_BYTES are rounded and clipped to
     integers between 0 and 255.  This byte stream is then mapped into
     the code page given by the string CODEPAGE and returned in the
     string UTF8_STR.  Octave uses UTF-8 as its internal encoding.  The
     string CODEPAGE must be an identifier of a valid code page.
     Examples for valid code pages are "ISO-8859-1", "Shift-JIS", or
     "UTF-16".  For a list of supported code pages, see
     <https://www.gnu.org/software/libiconv>.  If CODEPAGE is omitted or
     empty, the system default codepage is used.

     If NATIVE_BYTES is a string vector, it is returned as is.

     See also: *note unicode2native: XREFunicode2native.

 -- : do_string_escapes (STRING)
     Convert escape sequences in STRING to the characters they
     represent.

     Escape sequences begin with a leading backslash (’\’) followed by
     1–3 characters (.e.g., "\n" => newline).

     See also: *note undo_string_escapes: XREFundo_string_escapes.

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

     See also: *note do_string_escapes: XREFdo_string_escapes.


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 ]

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

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

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

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

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

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

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

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

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

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

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

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

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

 -- : 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 three different mechanisms to contain
arbitrary data types in the same variable: Structures, which are C-like,
and are indexed with named fields; containers.Map objects, which store
data in key/value pairs; 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::
* containers.Map::
* Cell Arrays::
* Comma Separated Lists::


File: octave.info,  Node: Structures,  Next: containers.Map,  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.

 -- : VAL = struct_levels_to_print ()
 -- : OLD_VAL = struct_levels_to_print (NEW_VAL)
 -- : 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.

 -- : VAL = print_struct_array_contents ()
 -- : OLD_VAL = print_struct_array_contents (NEW_VAL)
 -- : 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 1-by-2 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:language-extension’ 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
             }

 -- : S = struct ()
 -- : S = struct (FIELD1, VALUE1, FIELD2, VALUE2, ...)
 -- : 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 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 getfield: XREFgetfield, *note setfield:
     XREFsetfield, *note rmfield: XREFrmfield, *note isfield:
     XREFisfield, *note orderfields: XREForderfields, *note isstruct:
     XREFisstruct, *note structfun: XREFstructfun.

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

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

 -- : numfields (S)
     Return the number of fields of the structure S.

     See also: *note fieldnames: XREFfieldnames.

 -- : NAMES = fieldnames (STRUCT)
 -- : NAMES = fieldnames (OBJ)
 -- : NAMES = fieldnames (JAVAOBJ)
 -- : NAMES = fieldnames ("JAVACLASSNAME")
     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 a string containing the
     name of a Java class JAVACLASSNAME, the names are the public fields
     (data members) of the object or class.

     See also: *note numfields: XREFnumfields, *note isfield:
     XREFisfield, *note orderfields: XREForderfields, *note struct:
     XREFstruct, *note methods: XREFmethods.

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

 -- : SOUT = setfield (S, FIELD, VAL)
 -- : SOUT = setfield (S, SIDX1, FIELD1, FIDX1, SIDX2, FIELD2, FIDX2,
          ..., VAL)

     Return a _copy_ of the structure S with the field member FIELD set
     to the value 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 because of
     the space character.  Using arbitrary strings for field names is
     incompatible with MATLAB, and this usage will emit a warning if the
     warning ID ‘Octave:language-extension’ is enabled.  *Note
     warning_ids: XREFwarning_ids.

     With the second calling form, set a field of a structure array.
     The input SIDX selects an element of the structure array, FIELD
     specifies the field name of the selected element, and FIDX selects
     which element of the field (in the case of an array or cell array).
     The SIDX, FIELD, and FIDX inputs can be repeated to address nested
     structure array elements.  The structure array index and field
     element index must be cell arrays while the field name must be a
     string.

     For example:

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

     The example begins with an ordinary scalar structure to which a
     nested scalar structure is added.  In all cases, if the structure
     index SIDX is not specified it defaults to 1 (scalar structure).
     Thus, the example above could be written more concisely as
     ‘setfield (S, "foo", "bar", 54)’

     Finally, an example with nested structure arrays:

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

     Here SA is a structure array whose field at elements 1 and 2 is in
     turn another structure array whose third element is a simple scalar
     structure.  The terminal scalar structure has a field which
     contains a matrix value.

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

          SA.foo = 1;
          SA(2).bar(3).baz(1,4) = 5

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

 -- : VAL = getfield (S, FIELD)
 -- : VAL = getfield (S, SIDX1, FIELD1, FIDX1, ...)
     Get the value of the field named FIELD from a structure or nested
     structure S.

     If S is a structure array then SIDX selects an element of the
     structure array, FIELD specifies the field name of the selected
     element, and FIDX selects which element of the field (in the case
     of an array or cell array).  See ‘setfield’ for a more complete
     description of the syntax.

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

 -- : SOUT = rmfield (S, "F")
 -- : SOUT = 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, *note isfield: XREFisfield.

 -- : SOUT = orderfields (S1)
 -- : SOUT = orderfields (S1, S2)
 -- : SOUT = orderfields (S1, {CELLSTR})
 -- : SOUT = orderfields (S1, P)
 -- : [SOUT, P] = orderfields (...)
     Return a _copy_ of S1 with fields arranged alphabetically, or as
     specified by the second input.

     Given one input struct S1, arrange field names alphabetically.

     If a second struct argument is given, arrange field names in S1 as
     they appear in S2.  The second argument may also specify the order
     in a cell array of strings CELLSTR.  The second argument may also
     be a permutation vector.

     The optional second output argument P is the permutation vector
     which converts the original name order to 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 fieldnames: XREFfieldnames, *note getfield:
     XREFgetfield, *note setfield: XREFsetfield, *note rmfield:
     XREFrmfield, *note isfield: XREFisfield, *note isstruct:
     XREFisstruct, *note struct: XREFstruct.

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

 -- : 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: containers.Map,  Next: Cell Arrays,  Prev: Structures,  Up: Data Containers

6.2 containers.Map
==================

 -- : M = containers.Map ()
 -- : M = containers.Map (KEYS, VALS)
 -- : M = containers.Map (KEYS, VALS, "UniformValues", IS_UNIFORM)
 -- : M = containers.Map ("KeyType", KT, "ValueType", VT)

     Create an object of the containers.Map class that stores a list of
     key/value pairs.

     KEYS is an array of _unique_ keys for the map.  The keys can be
     numeric scalars or strings.  The type for numeric keys may be one
     of "double", "single", "int32", "uint32", "int64", or "uint64".
     Other numeric or logical keys will be converted to "double".  A
     single string key may be entered as is.  Multiple string keys are
     entered as a cell array of strings.

     VALS is an array of values for the map with the _same_ number of
     elements as KEYS.

     When called with no input arguments a default map is created with
     strings as the key type and "any" as the value type.

     The "UniformValues" option specifies whether the values of the map
     must be strictly of the same type.  If IS_UNIFORM is true, any
     values which would be added to the map are first validated to
     ensure they are of the correct type.

     When called with "KeyType" and "ValueType" arguments, create an
     empty map with the specified types.  The inputs KT and VT are the
     types for the keys and values of the map respectively.  Allowed
     values for KT are "char", "double", "single", "int32", "uint32",
     "int64", "uint64".  Allowed values for VT are "any", "char",
     "double", "single", "int32", "uint32", "int64", "uint64",
     "logical".

     The return value M is an object of the containers.Map class.

     See also: *note struct: XREFstruct.


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

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

 -- : celldisp (C)
 -- : 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


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

 -- : cell (N)
 -- : cell (M, N)
 -- : cell (M, N, K, ...)
 -- : 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.

 -- : C = num2cell (A)
 -- : 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.

 -- : C = mat2cell (A, M, N)
 -- : C = mat2cell (A, D1, D2, ...)
 -- : 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.

 -- : 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.3.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] = y
               [3,2] = 5
               [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.

 -- : Y = cellindexmat (X, VARARGIN)
     Perform indexing of matrices in a cell array.

     Given a cell array of matrices X, this function computes

          Y = cell (size (X));
          for i = 1:numel (X)
            Y{i} = X{i}(varargin{1}, varargin{2}, ..., varargin{N});
          endfor

     The indexing arguments may be scalar (‘2’), arrays (‘[1, 3]’),
     ranges (‘1:3’), or the colon operator (":").  However, the indexing
     keyword ‘end’ is not available.

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

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

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

     See also: *note ischar: XREFischar, *note isstring: XREFisstring.


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

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

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

 -- : cell2struct (CELL, FIELDS)
 -- : 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.4 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.4.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];
     in{2} = inf;
     in{3} = "last";
     in{4} = "first";
     out = cell (4, 1);
     [out{1:3}] = in{1 : 3};
     [out{4:6}] = in{[1, 2, 4]})
          ⇒ out =
             {
                [1,1] =

                   10   20   30

                [2,1] = Inf
                [3,1] = last
                [4,1] =

                   10   20   30

                [5,1] = Inf
                [6,1] = first
             }


File: octave.info,  Node: Comma Separated Lists Generated from Structure Arrays,  Prev: Comma Separated Lists Generated from Cell Arrays,  Up: Comma Separated Lists

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

 -- : isvarname (NAME)
     Return true if NAME is a valid variable name.

     See also: *note iskeyword: XREFiskeyword, *note exist: XREFexist,
     *note who: XREFwho.

 -- : VARNAME = genvarname (STR)
 -- : VARNAME = genvarname (STR, EXCLUSIONS)
     Create valid unique variable name(s) from STR.

     If STR is a cellstr, then a unique variable is created for each
     cell in STR.

          genvarname ({"foo", "foo"})
            ⇒
               {
                 [1,1] = foo
                 [1,2] = foo1
               }

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

          x = 3.141;
          genvarname ("x", who ())
            ⇒ x1

     Note that the result is a char array or 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

     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’ will replace any sequence of disallowed
     characters with an underscore.  Also, variables may not begin with
     a digit; in this case an ‘x’ 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 ensure 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 EXCLUSIONS
     if necessary.

     See also: *note isvarname: XREFisvarname, *note iskeyword:
     XREFiskeyword, *note exist: XREFexist, *note who: XREFwho, *note
     tempname: XREFtempname, *note eval: XREFeval.

 -- : 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 returned by
     ‘namelengthmax’.  In particular, variables stored to a MATLAB file
     format (‘*.mat’) will have their names truncated to this length.

* Menu:

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

