Copyright © 1996-2023 The Octave Project Developers
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.
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 8.2.0.
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 (http://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 (see GNU GENERAL PUBLIC LICENSE). 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.
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 | Andreas Bertsatos | Atri Bhattacharya |
Ethan Biery | David Billinghurst | Don Bindner |
Jakub Bogusz | Gaël Bonithon | Moritz Borgmann |
Paul Boven | Richard Bovey | John Bradshaw |
Marcus Brinkmann | Max Brister | Remy Bruno |
Stefan Brüns | Clemens Buchacher | Ansgar Burchard |
Antonius Burgers | 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 | Abdallah K. Elshamy | 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 Frias |
Brad Froehle | Castor Fu | Eduardo Gallestey |
Walter Gautschi | Klaus Gebhardt | Driss Ghaddab |
Eugenio Gianniti | Hartmut Gimpel | Michele Ginesi |
Nicolo Giorgetti | Arun Giridhar | Michael D. Godfrey |
Dave Goel | 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. Hadisoeseno | Jaroslav Hajek |
Benjamin Hall | Alexander Hansen | Kim Hansen |
Gene Harvey | 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 |
Christian Himpe | Ryan Hinton | Roman Hodek |
A. Scottedward Hodel | Júlio Hoffimann | 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 | Marcel Jacobse |
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 | Christof Kaufmann | Joel Keay |
Mumit Khan | Paul Kienzle | Lars Kindermann |
Aaron A. King | Erik Kjellson | Arno J. Klaassen |
Alexander Klein | Lasse Kliemann | Geoffrey Knauth |
Martin Köhler | Heine Kolltveit | Ken Kouno |
Kacper Kowalik | Endre Kozma | Daniel Kraft |
Nir Krakauer | Aravindh Krishnamoorthy | Oyvind Kristiansen |
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 | Andrej Lojdl | 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 | Markus Meisinger | Júlio Hoffimann Mendes |
Ed Meyer | Thorsten Meyer | Stefan Miereis |
Petr Mikulik | Mike Miller | Serviscope Minor |
Stefan Monnier | Rafael Monteiro | Stephen Montgomery-Smith |
Anthony Morast | Antoine Moreau | Kai P. Mueller |
Amod Mulay | Armin Müller | Hannes Müller |
Victor Munoz | PrasannaKumar Muralidharan | Iain Murray |
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 | Serkan Önder |
Arno Onken | Valentin Ortega-Clavero | Luis F. Ortiz |
Carl Osterwisch | Janne Olavi Paanajärvi | Óvári |
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 | Reinhard Resch | 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 |
Imad-Eddine Srairi | 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 Tennyhg | Remi Thebault | Kris Thielemans |
Georg Thimm | Paul Thomas | 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 | Steven Waldrip |
Thomas Walter | Jun Wang | 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 |
Eddy Xiao | 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:
This project would not have been possible without the GNU software used in and to produce Octave.
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
.
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.
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. See Known Causes of Trouble, for tips on how to write useful bug reports.
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 GNU GENERAL PUBLIC LICENSE.
To download a copy of Octave, please visit https://www.octave.org/download.html.
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, see GNU GENERAL PUBLIC LICENSE.
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 8.2.0.
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.
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.
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)
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
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
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
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.
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 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.
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 Commands for 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, see Commands for Getting Help.
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, see Command Line Editing.
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.
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.
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)
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
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
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.
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
:
(x)
¶(x, y)
¶(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.
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:
on
¶off
¶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:
Start recording a session in a file called diary in the current working directory.
Stop recording the session in the diary file.
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.
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.
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).
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 be 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.
--doc-cache-file filename
¶Specify the name of the documentation 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 call the
EXEC_PATH
function.
--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 call the IMAGE_PATH
function.
--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.
--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 optimize_diagonal_matrix = false optimize_permutation_matrix = false optimize_range = false fixed_point_format = true history_timestamp_format_string = "%%-- %D %I:%M %p --%%" print_empty_dimensions = false print_struct_array_contents = true save_default_options = "-mat-binary" struct_levels_to_print = 0
and disable the following warnings
Octave:abbreviated-property-match Octave:colon-nonscalar-argument Octave:data-file-in-path Octave:empty-index 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 (see warning,
warning_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.
args =
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. See Executable Octave Programs, for
an example of how to create an executable Octave script.
See also: program_name, cmdline_options.
opt_struct =
cmdline_options ()
¶Return a structure containing detailed information about the command line arguments passed to Octave.
Programming Note: This function provides copious amounts of information about Octave’s parsing of command line options and may be more useful for debugging Octave rather than for general use.
See also: argv, program_name.
name =
program_name ()
¶Return the filename component of the value returned by
program_invocation_name
.
See also: program_invocation_name, argv.
name =
program_invocation_name ()
¶Return the string that was typed at the shell prompt to run Octave.
The string may include path components as well as the program filename.
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. See Executable Octave Programs, for an example of how to create an
executable Octave script.
See also: program_name, argv.
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");
See Indexing Cell Arrays, for an explanation of how to retrieve objects
from cell arrays, and Defining Functions, for information about the
variable nargin
.
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
.
config-dir/octave/octaverc
¶where config-dir
is the platform-dependent location for user
local configuration files (e.g., $XDG_CONFIG_HOME
on many Unix-like
operating systems or %APPDATA%
on Windows).
~/.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.
The startup files are always processed in the system’s locale charset
(independent of the m-file encoding that is set, for example, in the GUI
properties). In other words, the system’s locale charset is in effect until a
user manually sets the m-file encoding (e.g., in one of the startup files) and
triggers re-parsing of any relevant m-files. Octave can be forced to use a
new encoding with the undocumented function __mfile_encoding__
:
__mfile_encoding__ ("utf-8"); # set new encoding clear ("functions"); # re-parse all .m files in the new encoding
This changes the encoding that is used to interpret all subsequently run startup and m-files (not including the currently executing file).
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
.
cancel
¶force
¶("cancel")
¶("force")
¶(status)
¶(status, "force")
¶Quit the current Octave session.
The exit
function is an alias for quit
.
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
. If an error occurs while executing the
finish.m file, Octave does not exit and control is returned to
the command prompt.
If the optional argument "cancel"
is provided, Octave does not
exit and control is returned to the command prompt. This feature allows
the finish.m
file to cancel the quit process.
If the user preference to request confirmation before exiting, Octave will display a dialog and give the user an option to cancel the exit process.
If the optional argument "force"
is provided, no confirmation is
requested, and the execution of the finish.m file is skipped.
See also: atexit.
(fcn)
¶(fcn, true)
¶(fcn, false)
¶status =
atexit (fcn, false)
¶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.
The optional output status is only available when unregistering a function. The value is true if the unregistering was successful and false otherwise.
Programming Note: atexit
only removes the first occurrence of a function
from the list; if a function was placed in the list multiple times with
atexit
, it must also be removed from the list multiple times.
See also: quit.
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. See Function Files, for more information about how to document the functions you write.
name
¶--list
¶.
¶help_text =
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.
function_name
¶Display documentation for the function function_name directly from an online version of the printed manual, using the GNU Info browser.
If invoked without 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: help.
str
¶-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. For more information,
see doc_cache_create
.
See also: help, doc, which, path, doc_cache_create.
To see what is new in the current release of Octave, use the news
function.
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.
()
¶Display contact information for the GNU Octave community.
()
¶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)
¶old_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/share/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: info_program, doc, help, makeinfo_program.
val =
info_program ()
¶old_val =
info_program (new_val)
¶old_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 info. 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: info_file, doc, help, makeinfo_program.
val =
makeinfo_program ()
¶old_val =
makeinfo_program (new_val)
¶old_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: texi_macros_file, info_file, info_program, doc, help.
val =
texi_macros_file ()
¶old_val =
texi_macros_file (new_val)
¶old_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: makeinfo_program.
val =
doc_cache_file ()
¶old_val =
doc_cache_file (new_val)
¶old_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: doc_cache_create, lookfor, info_program, doc, help, makeinfo_program.
See also: lookfor.
val =
built_in_docstrings_file ()
¶old_val =
built_in_docstrings_file (new_val)
¶old_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)
¶old_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.
(out_file, directory)
¶(out_file)
¶()
¶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: doc_cache_file, lookfor, path.
[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: get_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: get_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. If the text must be truncated the last
three characters of the text are replaced with "..."
to indicate
that more text was available.
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.
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.
readline
The following commands allow you to position the cursor.
Move back one character.
Move forward one character.
Delete the character to the left of the cursor.
Delete the character underneath the cursor.
Delete the character underneath the cursor.
Move forward a word.
Move backward a word.
Move to the start of the line.
Move to the end of the line.
Clear the screen, reprinting the current line at the top.
Undo the last action. You can undo all the way back to an empty line.
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.
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.
Kill the text from the current cursor position to the end of the line.
Kill from the cursor to the end of the current word, or if between words, to the end of the next word.
Kill from the cursor to the start of the previous word, or if between words, to the start of the previous word.
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.
Yank the most recently killed text back into the buffer at the cursor.
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.
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.
Add the next character that you type to the line verbatim. This is how to insert things like C-q for example.
Insert a tab character.
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.
Drag the word behind the cursor past the word in front of the cursor moving the cursor over that word as well.
Uppercase the characters following the cursor to the end of the current (or following) word, moving the cursor to the end of the word.
Lowercase the characters following the cursor to the end of the current (or following) word, moving the cursor to the end of the word.
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.
The following commands allow Octave to complete command and variable names for you.
Attempt to do completion on the text before the cursor. Octave can complete the names of commands and variables.
List the possible completions of the text before the cursor.
val =
completion_append_char ()
¶old_val =
completion_append_char (new_val)
¶old_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_list =
completion_matches ("hint")
¶Generate possible word completions for Octave given the character sequence hint.
This function is provided for the benefit of programs like Emacs which might be controlling Octave and handling user input. For example:
completion_matches ("sine") ⇒ sinetone sinewave
Programming Note: The current command number in Octave is not incremented when this function is called. This is a feature, not a bug.
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.
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.
Move ‘up’ through the history list.
Move ‘down’ through the history list.
Move to the first line in the history.
Move to the end of the input history, i.e., the line you are entering!
Search backward starting at the current line and moving ‘up’ through the history as necessary. This is an incremental search.
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.
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: edit_history, run_history.
cmd_number
¶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: run_history, history.
cmd_number
¶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: edit_history, history.
Octave also allows you customize the details of when, where, and how history is saved.
val =
history_save ()
¶old_val =
history_save (new_val)
¶old_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: history_control, history_file, history_size, history_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: history_file, history_size, history_timestamp_format_string, history_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.
All future commands issued during the current Octave session will be written to
this new file (if the current setting of history_save
allows for this).
The default value is $DATA
/octave/history, where
$DATA
is the platform-specific location for (roaming) user data files
(e.g., $XDG_DATA_HOME
or, if that is not set, ~/.local/share
on Unix-like operating systems or %APPDATA%
on Windows). The default
value may be overridden by the environment variable OCTAVE_HISTFILE
.
Programming Notes:
If you want to permanently change the location of Octave’s history file you
need to issue the history_file
command in every new Octave session.
This can be achieved by using Octave’s .octaverc startup file.
If you also want to read the saved history commands of past Octave sessions
from this different history file, then you need to use the additional command
history -r
after setting the new value of the history file. Example
code in Octave’s startup file to do this might look like this:
history_file ("~/new/.octave_hist"); if (exist (history_file ())) history ("-r", history_file()); endif
See also: history, history_control, history_save, history_size, history_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: history_file, history_timestamp_format_string, history_save.
val =
history_timestamp_format_string ()
¶old_val =
history_timestamp_format_string (new_val)
¶old_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: strftime, history_file, history_size, history_save.
val =
EDITOR ()
¶old_val =
EDITOR (new_val)
¶old_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: edit, edit_history.
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.
()
¶(file)
¶Read the readline library initialization file file.
If file is omitted, read the default initialization file (normally ~/.inputrc).
See Readline Init File in GNU Readline Library, for details.
See also: readline_re_read_init_file.
()
¶Re-read the last readline library initialization file that was read.
See Readline Init File in GNU Readline Library, for details.
See also: readline_read_init_file.
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:
The time.
The date.
Begins a new line by printing the equivalent of a carriage return followed by a line feed.
The name of the program (usually just ‘octave’).
The current working directory.
The basename of the current working directory.
The username of the current user.
The hostname, up to the first ‘.’.
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 ‘$’.
The character whose character code in octal is nnn.
A backslash.
val =
PS1 ()
¶old_val =
PS1 (new_val)
¶old_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. See 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.
val =
PS2 ()
¶old_val =
PS2 (new_val)
¶old_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.
val =
PS4 ()
¶old_val =
PS4 (new_val)
¶old_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 "+ "
.
See 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.
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.
on
¶off
¶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:
Start recording a session in a file called diary in the current working directory.
Stop recording the session in the diary file.
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.
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.
on
¶off
¶on all
¶off all
¶function on
¶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: PS4.
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 z = f (x, y) z = x ||| 2; endfunction
Octave will respond immediately with a message like this:
parse error: syntax error >>> function z = f (x, y) z = x ||| y; 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
the logical or operator (||
) 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.
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. See 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");
To write m-files that can act as executable programs when called from the shell
or as normal functions when called from within Octave, use default input
arguments initialized with the argv
function.
If a function is called from the shell Octave will not pass any input parameters to the function and therefore the default argument is used. But when a function is called from the interpreter any arguments are passed to the function and these override the default.
Additionally, the file must end with the extension .m so that the
interpreter will recognize it as an Octave function. Finally, the output from
argv
is a cell array of strings. It may be necessary to convert this
to a numeric value with str2double
or str2num
before processing.
As a complete example, consider the following code located in the file mysin.m.
#! /bin/octave -qf function retval = mysin (x = str2double (argv(){end})) retval = sin (x) endfunction
This can be called from the shell with
mysin.m 1.5
or from Octave with
mysin (1.5)
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.
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
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.
The help
command (see Commands for 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
(see Single Line Comments) and not block comments for the initial
help text.
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. See External Code Interface, for more information about Octave’s dynamic linking capabilities. User-defined Data Types describes what you must do to define a new data type for Octave.
typestr =
typeinfo (expr)
¶cstr =
typeinfo ()
¶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.
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)
¶cls =
class (s, classname)
¶cls =
class (s, classname, parent1, …)
¶Return the class of the object obj, or create a class with fields from structure s and name (string) classname.
Additional arguments name a list of parent classes from which the new class is derived.
tf =
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.
y =
cast (x, "type")
¶y =
cast (x, "like", var)
¶Convert x to data type type.
The input x may be a scalar, vector, or matrix of a class that is convertible to the target class (see below).
If a variable var is specified after "like"
, x is
converted to the same data type and sparsity attribute. If var is
complex, x will be complex, too.
var may be and type may name any of the following built-in numeric classes:
"double" "single" "logical" "char" "int8" "int16" "int32" "int64" "uint8" "uint16" "uint32" "uint64"
The value x 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 x 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: typecast, int8, uint8, int16, uint16, int32, uint32, int64, uint64, double, single, logical, char, class, typeinfo.
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]
y =
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
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.
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.
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. See Index Expressions.
See Numeric Data Types, for more information.
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
.
val =
NA ¶val =
NA (n)
¶val =
NA (n, m)
¶val =
NA (n, m, k, …)
¶val =
NA (…, "like", var)
¶val =
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.
If a variable var is specified after "like"
, the output val
will have the same data type, complexity, and sparsity as var.
The optional argument class specifies the return type and may be
either "double"
or "single"
.
See also: isna.
tf =
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 ]
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.
See Strings, for more information.
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.
See Structures, for more information.
A Cell Array in Octave is general array that can hold any number of different data types.
See Cell Arrays, for more information.
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.
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.
n =
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, i.e., trailing dimensions d
greater than 2 for which size (A, d) = 1
.
ndims (ones (4, 1, 2, 1)) ⇒ 3
See also: size.
nc =
columns (A)
¶Return the number of columns of A.
This is equivalent to size (A, 2)
.
See also: rows, size, length, numel, isscalar, isvector, ismatrix.
nr =
rows (A)
¶Return the number of rows of A.
This is equivalent to size (A, 1)
.
See also: columns, size, length, numel, isscalar, isvector, ismatrix.
n =
numel (A)
¶n =
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
.
n =
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))
).
sz =
size (A)
¶dim_sz =
size (A, dim)
¶dim_sz =
size (A, d1, d2, …)
¶[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. If dim is a vector, return each of the corresponding dimensions. Multiple dimensions may also be specified as separate arguments.
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 than 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: numel, ndims, length, rows, columns, size_equal, common_size.
tf =
isempty (A)
¶Return true if A is an empty matrix (any one of its dimensions is zero).
tf =
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
TF =
size_equal (A, B)
¶TF =
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: size, numel, ndims, common_size.
B =
squeeze (A)
¶Remove singleton dimensions from A 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: reshape.
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 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
z =
complex (x)
¶z =
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 ]
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.
max_numel =
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: intmax.
When you type a matrix or the name of a variable whose value is a matrix, Octave responds by printing the matrix in with neatly aligned rows and columns. If the rows of the matrix are too large to fit on the screen, Octave splits the matrix and displays a header before each section to indicate which columns are being displayed. You can use the following variables to control the format of the output.
val =
output_precision ()
¶old_val =
output_precision (new_val)
¶old_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. Also, calls to the
format
function that change numeric display can also change the set
value for output_precision
.
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: format, fixed_point_format.
It is possible to achieve a wide range of output styles by using
different values of output_precision
. Reasonable combinations can be
set using the format
function. See Basic Input and Output.
val =
split_long_rows ()
¶old_val =
split_long_rows (new_val)
¶old_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: format.
Octave automatically switches to scientific notation when values become
very large or very small. This guarantees that you will see several
significant figures for every value in a matrix. If you would prefer to
see all values in a matrix printed in a fixed point format, you can use
the function fixed_point_format
. 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)
¶old_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:
fixed_point_format (true) 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: format, output_precision.
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)
¶old_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: format.
Empty matrices may also be used in assignment statements as a convenient way to delete rows or columns of matrices. See Assignment Expressions.
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.
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 optimize_range.
val =
optimize_range ()
¶old_val =
optimize_range (new_val)
¶old_val =
optimize_range (new_val, "local")
¶Query or set whether a special space-efficient format is used for storing ranges.
The default value is true. If this option is set to false, Octave will store ranges as full matrices.
When called from inside a function with the "local"
option, the setting
is changed locally for the function and any subroutines it calls. The original
setting is restored when exiting the function.
See also: optimize_diagonal_matrix, optimize_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 (see 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.
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.
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.
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.
tf =
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: isfloat, ischar, islogical, isstring, isnumeric, isa.
y =
int8 (x)
¶Convert x to 8-bit integer type.
See also: uint8, int16, uint16, int32, uint32, int64, uint64.
y =
uint8 (x)
¶Convert x to unsigned 8-bit integer type.
See also: int8, int16, uint16, int32, uint32, int64, uint64.
y =
int16 (x)
¶Convert x to 16-bit integer type.
See also: int8, uint8, uint16, int32, uint32, int64, uint64.
y =
uint16 (x)
¶Convert x to unsigned 16-bit integer type.
y =
int32 (x)
¶Convert x to 32-bit integer type.
See also: int8, uint8, int16, uint16, uint32, int64, uint64.
y =
uint32 (x)
¶Convert x to unsigned 32-bit integer type.
y =
int64 (x)
¶Convert x to 64-bit integer type.
See also: int8, uint8, int16, uint16, int32, uint32, uint64.
y =
uint64 (x)
¶Convert x to unsigned 64-bit integer type.
Imax =
intmax ()
¶Imax =
intmax ("type")
¶Imax =
intmax (var)
¶Return the largest integer that can be represented by a specific integer type.
The input is either a string "type"
specifying an integer type,
or it is an existing integer variable var.
Possible values for type are
"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"
.
Example Code - query an existing variable
x = int8 (1); intmax (x) ⇒ 127
Imin =
intmin ()
¶Imin =
intmin ("type")
¶Imin =
intmin (var)
¶Return the smallest integer that can be represented by a specific integer type.
The input is either a string "type"
specifying an integer type,
or it is an existing integer variable var.
Possible values for type are
"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"
.
Example Code - query an existing variable
x = int8 (1); intmin (x) ⇒ -128
Imax =
flintmax ()
¶Imax =
flintmax ("double")
¶Imax =
flintmax ("single")
¶Imax =
flintmax (var)
¶Return the largest integer that can be represented consecutively in a floating point value.
The input is either a string specifying a floating point type, or it is an existing floating point variable var.
The default type is "double"
, but "single"
is a valid option.
On IEEE 754 compatible systems, flintmax
is 2^{53} for
"double"
and 2^{24} for "single"
.
Example Code - query an existing variable
x = single (1); flintmax (x) ⇒ 16777216
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
.
C =
idivide (A, B, 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") ⇒ 0 0 idivide (int8 ([-3, 3]), int8 (4), "round") ⇒ -1 1 idivide (int8 ([-3, 3]), int8 (4), "floor") ⇒ -1 0 idivide (int8 ([-3, 3]), int8 (4), "ceil") ⇒ 0 1
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
.
B =
bitset (A, n)
¶B =
bitset (A, n, val)
¶Set or reset bit(s) at position n of the unsigned integers in A.
The least significant bit is n = 1. val = 0 resets bits and val = 1 sets bits. If no val is specified it defaults to 1 (set bit). All inputs must be the same size or scalars.
Example 1: Set multiple bits
x = bitset (1, 3:5) ⇒ x = 5 9 17 dec2bin (x) ⇒ 00101 01001 10001
Example 2: Reset and set bits
x = bitset ([15 14], 1, [0 1]) ⇒ x = 14 15
See also: bitand, bitor, bitxor, bitget, bitcmp, bitshift, intmax, flintmax.
b =
bitget (A, n)
¶Return the bit value at position(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: bitand, bitor, bitxor, bitset, bitcmp, bitshift, intmax, flintmax.
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.
z =
bitand (x, y)
¶Return the bitwise AND of non-negative integers.
x, y must be in the range [0,intmax]
See also: bitor, bitxor, bitset, bitget, bitcmp, bitshift, intmax, flintmax.
z =
bitor (x, y)
¶Return the bitwise OR of non-negative integers x and y.
See also: bitor, bitxor, bitset, bitget, bitcmp, bitshift, intmax, flintmax.
z =
bitxor (x, y)
¶Return the bitwise XOR of non-negative integers x and y.
See also: bitand, bitor, bitset, bitget, bitcmp, bitshift, intmax, flintmax.
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
.
C =
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: bitand, bitor, bitxor, bitset, bitget, bitcmp, bitshift, flintmax.
Octave also includes the ability to left-shift and right-shift values bitwise.
B =
bitshift (A, k)
¶B =
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: bitand, bitor, bitxor, bitset, bitget, bitcmp, intmax, flintmax.
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]
.
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.
TF =
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.
val =
true (x)
¶val =
true (n, m)
¶val =
true (n, m, k, …)
¶val =
true (…, "like", var)
¶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.
If a logical variable var is specified after "like"
, the output
val will have the same sparsity as var.
See also: false.
val =
false (x)
¶val =
false (n, m)
¶val =
false (n, m, k, …)
¶val =
false (…, "like", var)
¶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.
If a logical variable var is specified after "like"
, the output
val will have the same sparsity as var.
See also: true.
Many operators and functions can work with mixed data types. For example,
uint8 (1) + 1 ⇒ 2
single (1) + 1 ⇒ 2
min (single (1), 0) ⇒ 0
where the results are respectively of types uint8, single, and single respectively. This is done for MATLAB compatibility. Valid mixed operations are defined as follows:
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 |
When functions expect a double but are passed other types, automatic conversion is function-dependent:
a = det (int8 ([1 2; 3 4])) ⇒ a = -2 class (a) ⇒ double
a = eig (int8 ([1 2; 3 4])) ⇒ error: eig: wrong type argument 'int8 matrix'
When two operands are both integers but of different widths, then some cases convert them to the wider bitwidth, and other cases throw an error:
a = min (int8 (100), int16 (200)) ⇒ 100 class (a) ⇒ int16
int8 (100) + int16 (200) ⇒ error: binary operator '+' not implemented for 'int8 scalar' by 'int16 scalar' operations
For two integer operands, they typically need to both be signed or both be unsigned. Mixing signed and unsigned usually causes an error, even if they are of the same bitwidth.
min (int16 (100), uint16 (200)) ⇒ error: min: cannot compute min (int16 scalar, uint16 scalar)
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.
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.
tf =
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: isinteger, isfloat, isreal, iscomplex, ischar, islogical, isstring, iscell, isstruct, isa.
tf =
islogical (x)
¶tf =
isbool (x)
¶Return true if x is a logical object.
See also: ischar, isfloat, isinteger, isstring, isnumeric, isa.
tf =
isfloat (x)
¶Return true if x is a floating-point numeric object.
Objects of class double or single are floating-point objects.
See also: isinteger, ischar, islogical, isnumeric, isstring, isa.
tf =
isreal (x)
¶Return true if x is a non-complex matrix or scalar.
For compatibility with MATLAB, this includes logical and character matrices.
tf =
iscomplex (x)
¶Return true if x is a complex-valued numeric object.
See also: isreal, isnumeric, ischar, isfloat, islogical, isstring, isa.
tf =
ismatrix (x)
¶Return true if x is a 2-D array.
A matrix is an object with two dimensions (ndims (x) == 2
) for
which size (x)
returns [M, N]
with non-negative M and
N.
See also: isscalar, isvector, iscell, isstruct, issparse, isa.
tf =
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 (either 1xN or Nx1). As a consequence of this definition, a 1x1 array (a scalar) is also a vector.
tf =
isrow (x)
¶Return true if x is a row vector.
A row vector is a 2-D array for which size (x)
returns
[1, N]
with non-negative N.
tf =
iscolumn (x)
¶Return true if x is a column vector.
A column vector is a 2-D array for which size (x)
returns
[N, 1]
with non-negative N.
tf =
isscalar (x)
¶Return true if x is a scalar.
A scalar is an object with two dimensions for which size (x)
returns [1, 1]
.
tf =
issquare (x)
¶Return true if x is a 2-D square array.
A square array is a 2-D object for which size (x)
returns
[N, N]
where N is a non-negative integer.
tf =
issymmetric (A)
¶tf =
issymmetric (A, tol)
¶tf =
issymmetric (A, "skew"
)
¶tf =
issymmetric (A, "skew"
, tol)
¶Return true if A is a symmetric or skew-symmetric matrix within the tolerance specified by tol.
The default tolerance is zero (uses faster code).
The type of symmetry to check may be specified with the additional input
"nonskew"
(default) for regular symmetry or "skew"
for
skew-symmetry.
Background: A matrix is symmetric if the transpose of the matrix is equal
to the original matrix: A == A.'
. If a tolerance
is given then symmetry is determined by
norm (A - A.', Inf) / norm (A, Inf) < tol
.
A matrix is skew-symmetric if the transpose of the matrix is equal to the
negative of the original matrix: A == -A.'
. If a
tolerance is given then skew-symmetry is determined by
norm (A + A.', Inf) / norm (A, Inf) < tol
.
See also: ishermitian, isdefinite.
tf =
ishermitian (A)
¶tf =
ishermitian (A, tol)
¶tf =
ishermitian (A, "skew"
)
¶tf =
ishermitian (A, "skew"
, tol)
¶Return true if A is a Hermitian or skew-Hermitian matrix within the tolerance specified by tol.
The default tolerance is zero (uses faster code).
The type of symmetry to check may be specified with the additional input
"nonskew"
(default) for regular Hermitian or "skew"
for
skew-Hermitian.
Background: A matrix is Hermitian if the complex conjugate transpose of the
matrix is equal to the original matrix: A == A'
. If
a tolerance is given then the calculation is
norm (A - A', Inf) / norm (A, Inf) < tol
.
A matrix is skew-Hermitian if the complex conjugate transpose of the matrix
is equal to the negative of the original matrix:
A == -A'
. If a
tolerance is given then the calculation is
norm (A + A', Inf) / norm (A, Inf) < tol
.
See also: issymmetric, isdefinite.
tf =
isdefinite (A)
¶tf =
isdefinite (A, tol)
¶Return true if A is symmetric positive definite matrix within the tolerance specified by tol.
If tol is omitted, use a tolerance of
100 * eps * norm (A, "fro")
.
Background: A positive definite matrix has eigenvalues which are all greater than zero. A positive semi-definite matrix has eigenvalues which are all greater than or equal to zero. The matrix A is very likely to be positive semi-definite if the following two conditions hold for a suitably small tolerance tol.
isdefinite (A) ⇒ 0 isdefinite (A + 5*tol, tol) ⇒ 1
See also: issymmetric, ishermitian.
tf =
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.
tf =
isdiag (A)
¶Return true if A is a diagonal matrix.
tf =
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.
tf =
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.
tf =
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 suitable for all x
in the range abs(x)
< 2^64.
Compatibility Note: MATLAB does not extend the definition of prime numbers and will produce an error if given negative or complex inputs.
If instead of knowing properties of variables, you wish to know which variables are defined and to gather other information about the workspace itself, see Status of Variables.
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 (see Arithmetic Operators) 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’. See Numeric Data Types, for more information about creating matrices.
While strings can in principle store arbitrary content, most functions expect them to be UTF-8 encoded Unicode strings.
Furthermore, it is 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).
str =
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: repmat.
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
.
tf =
is_dq_string (x)
¶Return true if x is a double-quoted character string.
See also: is_sq_string, ischar.
tf =
is_sq_string (x)
¶Return true if x is a single-quoted character string.
See also: is_dq_string, ischar.
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.
tf =
ischar (x)
¶Return true if x is a character array.
See also: isfloat, isinteger, islogical, isnumeric, isstring, iscellstr, isa.
tf =
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: ischar, iscellstr, isfloat, isinteger, islogical, isnumeric, isa.
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)
¶old_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.
Another useful function to control the text justification in this case is
the strjust
function.
str =
strjust (s)
¶str =
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"
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 Cell Arrays of 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.
The following functions are useful to perform common String operations.
y =
tolower (s)
¶y =
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"
Programming Note: lower
is an alias for tolower
and either name
can be used in Octave.
See also: toupper.
y =
toupper (s)
¶y =
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"
Programming Note: upper
is an alias for toupper
and either name
can be used in Octave.
See also: tolower.
s =
deblank (s)
¶Remove trailing whitespace and nulls from s.
If s is a matrix, deblank trims each row to the length of the 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: strtrim.
s =
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: deblank.
s =
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.
str =
untabify (t)
¶str =
untabify (t, tw)
¶str =
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);
newstr =
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: undo_string_escapes.
newstr =
undo_string_escapes (string)
¶Convert special characters in string 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: do_string_escapes.
Strings can be concatenated using matrix notation (see Strings, 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.
The newline
function can be used to join strings such that they appear
as multiple lines of text when displayed.
c =
newline ¶Return the character corresponding to a newline.
This is equivalent to "\n"
.
Example Code
joined_string = [newline "line1" newline "line2"] ⇒ line1 line2
In addition, 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 cat,
horzcat, and vertcat.
cstrcat
convert numerical input into character data by taking the corresponding UTF-8
character for each element (or multi-byte sequence), as in the following
example:
char ([98, 97, 110, 97, 110, 97]) ⇒ banana
For conversion between locale encodings and UTF-8, see unicode2native and native2unicode.
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
cstrcat
also accept cell
array data (see 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
(see Character Arrays).
C =
char (A)
¶C =
char (A, …)
¶C =
char (str1, str2, …)
¶C =
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"]
C =
strvcat (A)
¶C =
strvcat (A, …)
¶C =
strvcat (str1, str2, …)
¶C =
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"]
str =
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 }
str =
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"
str =
substr (s, offset)
¶(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.
[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
[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:
true
(default) or false
.
"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 }
[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 }
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: strsplit.
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.
tf =
strcmp (str1, str2)
¶Return 1 if the character strings str1 and str2 are the same, and 0 otherwise.
If either str1 or str2 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.
tf =
strncmp (str1, str2, n)
¶Return 1 if the first n characters of strings str1 and str2 are the same, and 0 otherwise.
strncmp ("abce", "abcd", 3) ⇒ 1
If either str1 or str2 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.
tf =
strcmpi (str1, str2)
¶Return 1 if the character strings str1 and str2 are the same, disregarding case of alphabetic characters, and 0 otherwise.
If either str1 or str2 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.
tf =
strncmpi (str1, str2, 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 str1 or str2 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.
Despite those comparison functions, there are more specialized function to find the index position of a search pattern within a string.
retval =
startsWith (str, pattern)
¶retval =
startsWith (str, pattern, "IgnoreCase", ignore_case)
¶Check whether string(s) start with pattern(s).
Return an array of logical values that indicates which string(s) in the input str (a single string or cell array of strings) begin with the input pattern (a single string or cell array of strings).
If the value of the parameter "IgnoreCase"
is true, then the
function will ignore the letter case of str and pattern. By
default, the comparison is case sensitive.
Examples:
## one string and one pattern while considering case startsWith ("hello", "he") ⇒ 1
## one string and one pattern while ignoring case startsWith ("hello", "HE", "IgnoreCase", true) ⇒ 1
## multiple strings and multiple patterns while considering case startsWith ({"lab work.pptx", "data.txt", "foundations.ppt"}, {"lab", "data"}) ⇒ 1 1 0
## multiple strings and one pattern while considering case startsWith ({"DATASHEET.ods", "data.txt", "foundations.ppt"}, "data", "IgnoreCase", false) ⇒ 0 1 0
## multiple strings and one pattern while ignoring case startsWith ({"DATASHEET.ods", "data.txt", "foundations.ppt"}, "data", "IgnoreCase", true) ⇒ 1 1 0
retval =
endsWith (str, pattern)
¶retval =
endsWith (str, pattern, "IgnoreCase", ignore_case)
¶Check whether string(s) end with pattern(s).
Return an array of logical values that indicates which string(s) in the input str (a single string or cell array of strings) end with the input pattern (a single string or cell array of strings).
If the value of the parameter "IgnoreCase"
is true, then the
function will ignore the letter case of str and pattern. By
default, the comparison is case sensitive.
Examples:
## one string and one pattern while considering case endsWith ("hello", "lo") ⇒ 1
## one string and one pattern while ignoring case endsWith ("hello", "LO", "IgnoreCase", true) ⇒ 1
## multiple strings and multiple patterns while considering case endsWith ({"tests.txt", "mydoc.odt", "myFunc.m", "results.pptx"}, {".docx", ".odt", ".txt"}) ⇒ 1 1 0 0
## multiple strings and one pattern while considering case endsWith ({"TESTS.TXT", "mydoc.odt", "result.txt", "myFunc.m"}, ".txt", "IgnoreCase", false) ⇒ 0 0 1 0
## multiple strings and one pattern while ignoring case endsWith ({"TESTS.TXT", "mydoc.odt", "result.txt", "myFunc.m"}, ".txt", "IgnoreCase", true) ⇒ 1 0 1 0
See also: startsWith, regexp, strncmp, strncmpi.
v =
findstr (s, t)
¶v =
findstr (s, t, overlap)
¶This function is obsolete. Use strfind
instead.
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 obsolete. Use strfind
in all new
code.
See also: strfind, strmatch, strcmp, strncmp, strcmpi, strncmpi, find.
idx =
strchr (str, chars)
¶idx =
strchr (str, chars, n)
¶idx =
strchr (str, chars, n, direction)
¶[i, j] =
strchr (…)
¶Search through 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: find.
n =
index (s, t)
¶n =
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.
n =
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"
.
idx =
unicode_idx (str)
¶Return an array with the indices for each UTF-8 encoded character in str.
unicode_idx ("aäbc") ⇒ [1, 2, 2, 3, 4]
idx =
strfind (str, pattern)
¶idx =
strfind (cellstr, pattern)
¶idx =
strfind (…, "overlaps", val)
¶idx =
strfind (…, "forcecelloutput", 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.
The optional argument "forcecelloutput"
forces idx to be
returned as a cell array of vectors. The default is false.
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) }
strfind ("abababa", "aba", "forcecelloutput", true) ⇒ { [1,1] = 1 3 5 }
idx =
strmatch (s, A)
¶idx =
strmatch (s, A, "exact")
¶This function is obsolete. Use an alternative such as
strncmp
or strcmp
instead.
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 obsolete (and can produce incorrect
results in MATLAB when used with cell arrays of strings. Use
strncmp
(normal case) or strcmp
("exact"
case) in all
new code. Other replacement possibilities, depending on application,
include regexp
or validatestring
.
See also: strncmp, strcmp, regexp, strfind, validatestring.
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"
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"
For processing overlaps, see strrep
.
[s, e, te, m, t, nm, sp] =
regexp (str, pat)
¶[…] =
regexp (str, pat, "opt1", …)
¶Regular expression string matching.
Search for pat in UTF-8 encoded 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
The start indices of each matching substring
The end indices of each matching substring
The extents of each matched token surrounded by (…)
in
pat
A cell array of the text of each match
A cell array of the text of each token matched
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>…)
.
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.
Return only the first occurrence of the pattern.
Make the matching case sensitive. (default)
Alternatively, use (?-i) in the pattern.
Ignore case when matching the pattern to the string.
Alternatively, use (?i) in the pattern.
Match the anchor characters at the beginning and end of the string. (default)
Alternatively, use (?-m) in the pattern.
Match the anchor characters at the beginning and end of the line.
Alternatively, use (?m) in the pattern.
The pattern .
matches all characters including the newline character.
(default)
Alternatively, use (?s) in the pattern.
The pattern .
matches all characters except the newline character.
Alternatively, use (?-s) in the pattern.
All characters in the pattern, including whitespace, are significant and are used in pattern matching. (default)
Alternatively, use (?-x) in the pattern.
The pattern may include arbitrary whitespace and also comments beginning with the character ‘#’.
Alternatively, use (?x) in the pattern.
Zero-length matches are not returned. (default)
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.
[s, e, te, m, t, nm, sp] =
regexpi (str, pat)
¶[…] =
regexpi (str, pat, "opt1", …)
¶Case insensitive regular expression string matching.
Search for pat in UTF-8 encoded str and return the positions and
substrings of any matches, or empty values if there are none.
See regexp
, for details on the syntax of the search
pattern.
See also: regexp.
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
.
See regexp
.
All strings must be UTF-8 encoded.
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
Replace only the first occurrence of pat in the result.
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.
str =
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'
Octave offers several kinds of conversion functions for Strings.
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: native2unicode.
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: unicode2native.
Apart from the string concatenation functions (see Concatenating Strings)
which cast numerical data to the corresponding UTF-8 encoded 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
(see Formatted Output, sprintf).
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
str =
num2str (x)
¶str =
num2str (x, precision)
¶str =
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
(see Formatted Output).
num2str
can also process complex numbers.
Examples:
num2str (123.456) ⇒ 123.456 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 ⇒ Variables in the current scope: Attr Name Size Bytes Class ==== ==== ==== ===== ===== s 2x8 16 char Total is 16 elements using 16 bytes num2str (1.234 + 27.3i) ⇒ 1.234+27.3i
The num2str
function is not very flexible. For better control
over the results, use sprintf
(see 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.
str =
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 ⇒ Variables in the current scope: Attr Name Size Bytes Class ==== ==== ==== ===== ===== s 2x7 14 char Total is 14 elements using 14 bytes
This function is not very flexible. For better control over the
results, use sprintf
(see Formatted Output).
Programming Notes:
Non-integers are rounded to integers before display. Only the real part of complex numbers is displayed.
d =
str2double (str)
¶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'
:
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.
str 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 str 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.
Programming Note: str2double
can replace str2num
, is more
efficient, and avoids the security risk of using eval
on unknown data.
See also: str2num.
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: str2double, eval.
d =
bin2dec (str)
¶Return the decimal number corresponding to the binary number represented by the string str.
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 str is a string matrix, return a column vector with one converted number per row of str; Invalid rows evaluate to NaN.
If str is a cell array of strings, return a column vector with one converted number per cell element in str.
bstr =
dec2bin (d)
¶bstr =
dec2bin (d, len)
¶Return a string of ones and zeros representing the conversion of the integer d to a binary number.
If d is a matrix or cell array, return a string matrix with one row for each 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.
For negative elements of d, return the binary value of the two’s complement. The result is padded with leading ones to 8, 16, 32, or 64 bits as appropriate for the magnitude of the input. Positive input elements are padded with leading zeros to the same width. If the second argument len exceeds that calculated width, the result is further padded with leading zeros, for compatibility with MATLAB.
Examples:
dec2bin (14) ⇒ "1110" dec2bin (-14) ⇒ "11110010"
Known MATLAB Incompatibility: MATLAB’s dec2bin
allows
non-integer values for d as of Release 2022b, but is inconsistent
with truncation versus rounding and is also inconsistent with its own
dec2hex
function. For self-consistency, Octave gives an error for
non-integer inputs. Users requiring compatible code for non-integer inputs
should make use of fix
or round
as appropriate.
hstr =
dec2hex (d)
¶hstr =
dec2hex (d, len)
¶Return a string representing the conversion of the integer d to a hexadecimal (base16) number.
If d is negative, return the hexadecimal equivalent of the two’s complement binary value of d. If d is a matrix or cell array, return a string matrix with one row for each 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.
Examples:
dec2hex (2748) ⇒ "ABC" dec2hex (-2) ⇒ "FE"
d =
hex2dec (str)
¶Return the integer corresponding to the hexadecimal number represented by the string str.
For example:
hex2dec ("12B") ⇒ 299 hex2dec ("12b") ⇒ 299
If str is a string matrix, return a column vector with one converted number per row of str; Invalid rows evaluate to NaN.
If str is a cell array of strings, return a column vector with one converted number per cell element in str.
str =
dec2base (d, base)
¶str =
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. Whitespace (spaces, tabs, newlines, , etc.) 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.
d =
base2dec (str, base)
¶Convert str from a string of digits in base base to a decimal integer (base 10).
base2dec ("11120", 3) ⇒ 123
If str is a string matrix, return a column vector with one value per row of str. If a row contains invalid symbols then the corresponding value will be NaN.
If str is a cell array of strings, return a column vector with one value per cell element in str.
If base is a string, the characters of base are used as the symbols for the digits of str. Space (’ ’) may not be used as a symbol.
base2dec ("yyyzx", "xyz") ⇒ 123
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.
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]
[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, …)
¶This function is obsolete. Use textscan
instead.
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:
(default) read all of the string until the end.
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.
"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:
"\n"
Data columns are padded with empty fields or NaN so that all columns have equal length
"\n"
Data columns are not padded; strread returns columns of unequal length
JavaScript Object Notation, in short JSON, is a very common human readable and structured data format. GNU Octave supports encoding and decoding this format with the following two functions.
JSON_txt =
jsonencode (object)
¶JSON_txt =
jsonencode (…, "ConvertInfAndNaN", TF)
¶JSON_txt =
jsonencode (…, "PrettyPrint", TF)
¶Encode Octave data types into JSON text.
The input object is an Octave variable to encode.
The output JSON_txt is the JSON text that contains the result of encoding object.
If the value of the option "ConvertInfAndNaN"
is true then NaN
,
NA
, -Inf
, and Inf
values will be converted to
"null"
in the output. If it is false then they will remain as their
original values. The default value for this option is true.
If the value of the option "PrettyPrint"
is true, the output text will
have indentations and line feeds. If it is false, the output will be condensed
and written without whitespace. The default value for this option is false.
Programming Notes:
"\n"
), use
single-quoted strings.
"\0"
) in a
double-quoted string will be dropped during encoding.
int8
and then decode it, you will get a double
.
This table shows the conversions from Octave data types to JSON data types:
Octave data type | JSON data type |
---|---|
logical scalar | Boolean |
logical vector | Array of Boolean, reshaped to row vector |
logical array | nested Array of Boolean |
numeric scalar | Number |
numeric vector | Array of Number, reshaped to row vector |
numeric array | nested Array of Number |
NaN , NA , Inf , -Inf when "ConvertInfAndNaN" = true | "null" |
NaN , NA , Inf , -Inf when "ConvertInfAndNaN" = false | "NaN" , "NaN" ,
"Infinity" , "-Infinity" |
empty array | "[]" |
character vector | String |
character array | Array of String |
empty character array | "" |
cell scalar | Array |
cell vector | Array, reshaped to row vector |
cell array | Array, flattened to row vector |
struct scalar | Object |
struct vector | Array of Object, reshaped to row vector |
struct array | nested Array of Object |
classdef object | Object |
Examples:
jsonencode ([1, NaN; 3, 4]) ⇒ [[1,null],[3,4]]
jsonencode ([1, NaN; 3, 4], "ConvertInfAndNaN", false) ⇒ [[1,NaN],[3,4]]
## Escape characters inside a single-quoted string jsonencode ('\0\a\b\t\n\v\f\r') ⇒ "\\0\\a\\b\\t\\n\\v\\f\\r"
## Escape characters inside a double-quoted string jsonencode ("\a\b\t\n\v\f\r") ⇒ "\u0007\b\t\n\u000B\f\r"
jsonencode ([true; false], "PrettyPrint", true) ⇒ ans = [ true, false ]
jsonencode (['foo', 'bar'; 'foo', 'bar']) ⇒ ["foobar","foobar"]
jsonencode (struct ('a', Inf, 'b', [], 'c', struct ())) ⇒ {"a":null,"b":[],"c":{}}
jsonencode (struct ('structarray', struct ('a', {1; 3}, 'b', {2; 4}))) ⇒ {"structarray":[{"a":1,"b":2},{"a":3,"b":4}]}
jsonencode ({'foo'; 'bar'; {'foo'; 'bar'}}) ⇒ ["foo","bar",["foo","bar"]]
jsonencode (containers.Map({'foo'; 'bar'; 'baz'}, [1, 2, 3])) ⇒ {"bar":2,"baz":3,"foo":1}
See also: jsondecode.
object =
jsondecode (JSON_txt)
¶object =
jsondecode (…, "ReplacementStyle", rs)
¶object =
jsondecode (…, "Prefix", pfx)
¶object =
jsondecode (…, "makeValidName", TF)
¶Decode text that is formatted in JSON.
The input JSON_txt is a string that contains JSON text.
The output object is an Octave object that contains the result of decoding JSON_txt.
For more information about the options "ReplacementStyle"
and
"Prefix"
,
see matlab.lang.makeValidName
.
If the value of the option "makeValidName"
is false then names
will not be changed by matlab.lang.makeValidName
and the
"ReplacementStyle"
and "Prefix"
options will be ignored.
NOTE: Decoding and encoding JSON text is not guaranteed to reproduce the
original text as some names may be changed by matlab.lang.makeValidName
.
This table shows the conversions from JSON data types to Octave data types:
JSON data type | Octave data type |
---|---|
Boolean | scalar logical |
Number | scalar double |
String | vector of characters |
Object | scalar struct (field names of the struct may be different from the keys of the JSON object due to matlab_lang_makeValidName |
null, inside a numeric array | NaN |
null, inside a non-numeric array | empty double array [] |
Array, of different data types | cell array |
Array, of Booleans | logical array |
Array, of Numbers | double array |
Array, of Strings | cell array of character vectors (cellstr ) |
Array of Objects, same field names | struct array |
Array of Objects, different field names | cell array of scalar structs |
Examples:
jsondecode ('[1, 2, null, 3]') ⇒ ans = 1 2 NaN 3
jsondecode ('["foo", "bar", ["foo", "bar"]]') ⇒ ans = { [1,1] = foo [2,1] = bar [3,1] = { [1,1] = foo [2,1] = bar } }
jsondecode ('{"nu#m#ber": 7, "s#tr#ing": "hi"}', ... 'ReplacementStyle', 'delete') ⇒ scalar structure containing the fields: number = 7 string = hi
jsondecode ('{"nu#m#ber": 7, "s#tr#ing": "hi"}', ... 'makeValidName', false) ⇒ scalar structure containing the fields: nu#m#ber = 7 s#tr#ing = hi
jsondecode ('{"1": "one", "2": "two"}', 'Prefix', 'm_') ⇒ scalar structure containing the fields: m_1 = one m_2 = two
See also: jsonencode, matlab.lang.makeValidName.
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 ]
tf =
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)
).
tf =
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: isdigit, ispunct, isspace, iscntrl, isalnum, islower, isupper.
tf =
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: isalpha, isdigit, ispunct, isspace, iscntrl, isalnum.
tf =
islower (s)
¶Return a logical array which is true where the elements of s are lowercase letters and false where they are not.
tf =
isupper (s)
¶Return a logical array which is true where the elements of s are uppercase letters and false where they are not.
tf =
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: isxdigit, isalpha, isletter, ispunct, isspace, iscntrl.
tf =
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: isdigit.
tf =
ispunct (s)
¶Return a logical array which is true where the elements of s are punctuation characters and false where they are not.
tf =
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.
tf =
iscntrl (s)
¶Return a logical array which is true where the elements of s are control characters and false where they are not.
tf =
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: isprint.
tf =
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: isgraph.
tf =
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.
tf =
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: isalpha, isalnum, islower, isupper, isdigit, isxdigit, isspace, ispunct, iscntrl, isgraph, isprint, isascii.
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.
Octave includes support for organizing data in structures. The current implementation uses an associative array with indices limited to strings, but the syntax is more like C-style structures.
Here are some examples of using data structures in Octave.
Elements of structures can be of any value type. For example, the three expressions
x.a = 1; x.b = [1, 2; 3, 4]; x.c = "string";
create a structure with three elements. The ‘.’ character separates
the structure name (in the example above x
) 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 = scalar structure containing the fields: 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 = scalar structure containing the fields: a = 1 b = 1 2 3 4 c = string
Since structures are themselves values, structure elements may reference
other structures, as well. The following statement adds the field d
to the structure x
. The value of field d
is itself a data
structure containing the single field a
, which has a value of 3.
x.d.a = 3; x.d ⇒ ans = scalar structure containing the fields: a = 3 x ⇒ x = scalar structure containing the fields: a = 1 b = 1 2 3 4 c = string d = scalar structure containing the fields: a = 3
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 = scalar structure containing the fields: b = scalar structure containing the fields: c = scalar structure containing the fields: d: 1x1 scalar 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)
¶old_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: print_struct_array_contents.
val =
print_struct_array_contents ()
¶old_val =
print_struct_array_contents (new_val)
¶old_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: struct_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 y
.
function y = f (x) y.re = real (x); y.im = imag (x); endfunction
When called with a complex-valued argument, the function f
returns
the data structure containing the real and imaginary parts of the original
function argument.
f (rand (2) + rand (2) * I) ⇒ ans = scalar structure containing the fields: re = 0.040239 0.242160 0.238081 0.402523 im = 0.26475 0.14828 0.18436 0.83669
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 = scalar structure containing the fields: 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
(see Looping Over Structure Elements).
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
(see 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 (see 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 (see 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
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. See warning_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: cell2struct, fieldnames, getfield, setfield, rmfield, isfield, orderfields, isstruct, structfun.
The function isstruct
can be used to test if an object is a
structure or a structure array.
tf =
isstruct (x)
¶Return true if x is a structure or a structure array.
Other functions that can manipulate the fields of a structure are given below.
n =
numfields (s)
¶Return the number of fields of the structure s.
See also: fieldnames.
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: numfields, isfield, orderfields, struct, properties.
tf =
isfield (x, "name")
¶tf =
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: fieldnames.
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.
See warning_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: getfield, rmfield, orderfields, isfield, fieldnames, isstruct, struct.
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). For a more complete description of the syntax,
see setfield
.
See also: setfield, rmfield, orderfields, isfield, fieldnames, isstruct, struct.
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: orderfields, fieldnames, isfield.
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 = scalar structure containing the fields: a = 1 b = 2 c = 3 d = 4
t = struct ("d", {}, "c", {}, "b", {}, "a", {}); t2 = orderfields (s, t) ⇒ t2 = scalar structure containing the fields: d = 4 c = 3 b = 2 a = 1
t3 = orderfields (s, [3, 2, 4, 1]) ⇒ t3 = scalar structure containing the fields: a = 1 b = 2 c = 3 d = 4
[t4, p] = orderfields (s, {"d", "c", "b", "a"}) ⇒ t4 = scalar structure containing the fields: d = 4 c = 3 b = 2 a = 1 p = 1 4 2 3
See also: fieldnames, getfield, setfield, rmfield, isfield, isstruct, struct.
s =
substruct (type, subs, …)
¶Create a subscript structure for use with subsref
or subsasgn
.
For example:
idx = substruct ("()", {3, ":"}) ⇒ idx = scalar structure containing the fields: type = () subs = { [1,1] = 3 [1,2] = : } x = [1, 2, 3; 4, 5, 6; 7, 8, 9]; subsref (x, idx) ⇒ 7 8 9
The simplest way to process data in a structure is within a for
loop (see 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.
See structfun.
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: cell2struct, namedargs2cell, fieldnames.
c =
namedargs2cell (s)
¶Create a cell array of field name/value pairs from a scalar structure.
Example:
s.Name = "Peter"; s.Height = 185; s.Age = 42; c = namedargs2cell (s) ⇒ { "Name", "Peter", "Height", 185, "Age", 42 }
See also: struct2cell.
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: struct.
It can be both necessary and convenient to store several variables of different size or type in one variable. A cell array is a container class able to do just that. In general cell arrays work just like N-dimensional arrays with the exception of the use of ‘{’ and ‘}’ as allocation and indexing operators.
As an example, the following code creates a cell array containing a string and a 2-by-2 random matrix
c = {"a string", rand(2, 2)};
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 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.
(c)
¶(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: disp.
To test if an object is a cell array, use the iscell
function. For example:
iscell (c) ⇒ ans = 1 iscell (3) ⇒ ans = 0
tf =
iscell (x)
¶Return true if x is a cell array object.
The introductory example (see 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 size function also works for cell arrays. As do other functions describing the size of an object, such as length, numel, rows, and columns.
C =
cell (n)
¶C =
cell (m, n)
¶C =
cell (m, n, k, …)
¶C =
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: cellstr, mat2cell, num2cell, struct2cell.
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.
When no dim is specified, each element of A becomes a 1x1 element in the output C.
If dim is defined then individual elements of C contain all of the elements from A along the specified dimension. dim may also be a vector of dimensions with the same rule applied.
For example:
x = [1,2;3,4] ⇒ 1 2 3 4 ## each element of A becomes a 1x1 element of C num2cell (x) ⇒ { [1,1] = 1 [2,1] = 3 [1,2] = 2 [2,2] = 4 } ## all rows (dim 1) of A appear in each element of C num2cell (x, 1) ⇒ { [1,1] = 1 3 [1,2] = 2 4 } ## all columns (dim 2) of A appear in each element of C num2cell (x, 2) ⇒ { [1,1] = 1 2 [2,1] = 3 4 } ## all rows and cols appear in each element of C ## (hence, only 1 output) num2cell (x, [1, 2]) ⇒ { [1,1] = 1 2 3 4 }
See also: mat2cell.
C =
mat2cell (A, dim1, dim2, …, dimi, …, dimn)
¶C =
mat2cell (A, rowdim)
¶Convert the matrix A to a cell array.
Each dimension argument (dim1, dim2, etc.) is a vector of
integers which specifies how to divide that dimension’s elements amongst the
new elements in the output C. The number of elements in the i-th
dimension is size (A, i)
. Because all elements in A
must be partitioned, there is a requirement that sum (dimi) == size
(A, i)
. The size of the output cell C is numel (dim1) x
numel (dim2) x … x numel (dimn).
Given a single dimensional argument, rowdim, the output is divided into rows as specified. All other dimensions are not divided and thus all columns (dim 2), pages (dim 3), etc. appear in each output element.
Examples
x = reshape (1:12, [3, 4])' ⇒ 1 2 3 4 5 6 7 8 9 10 11 12
## The 4 rows (dim1) are divided in to two cell elements ## with 2 rows each. ## The 3 cols (dim2) are divided in to three cell elements ## with 1 col each. mat2cell (x, [2,2], [1,1,1]) ⇒ { [1,1] = 1 4 [2,1] = 7 10 [1,2] = 2 5 [2,2] = 8 11 [1,3] = 3 6 [2,3] = 9 12 }
## The 4 rows (dim1) are divided in to two cell elements ## with a 3/1 split. ## All columns appear in each output element. mat2cell (x, [3,1]) ⇒ { [1,1] = 1 2 3 4 5 6 7 8 9 [2,1] = 10 11 12 }
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: cell2mat, cellindexmat, cellfun.
As shown in see 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 (see 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: cellslices, cellfun.
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
(see 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
.
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
(see Concatenating Strings), strcmp
, strncmp
, strcmpi
,
strncmpi
(see Searching in Strings), str2double
,
deblank
, strtrim
, strtrunc
, strfind
,
strmatch
, , regexp
, regexpi
(see String Operations) and str2double
(see Converting Strings).
The function iscellstr
can be used to test if an object is a
cell array of strings.
tf =
iscellstr (cell)
¶Return true if every element of the cell array cell is a character string.
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. See cellfun.
An alternative is to convert the data to a different container, such as
a matrix or a data structure. Depending on the data this is possible
using the cell2mat
and cell2struct
functions.
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.
S =
cell2struct (cell, fields)
¶S =
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.
S = cell2struct ({"Peter", "Hannah", "Robert"; 185, 170, 168}, {"Name","Height"}, 1); S(1) ⇒ { Name = Peter Height = 185 }
See also: struct2cell, cell2mat, struct.
Comma-separated lists 2 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 []
(see Matrices) or the
creation of a cell array with {}
(see 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.
As has been mentioned above (see 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 }
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);
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. See Assignment Expressions.
There is one automatically created 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.
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.
tf =
isvarname (name)
¶Return true if name is a valid variable name.
A valid variable name is composed of letters, digits, and underscores ("_"), and the first character must not be a digit.
varname =
matlab.lang.makeValidName (str)
¶varname =
matlab.lang.makeValidName (…, "ReplacementStyle"
, rs)
¶varname =
matlab.lang.makeValidName (…, "Prefix"
, pfx)
¶[varname, ismodified] =
matlab.lang.makeValidName (…)
¶Create valid variable name varname from str.
The input str must be a string or a cell array of strings. The output varname will be of the same type.
A valid variable name is a sequence of letters, digits, and underscores that does not begin with a digit.
The "ReplacementStyle"
option specifies how invalid characters
are handled. Acceptable values are
"underscore"
(default)Replace all invalid characters with an underscore ("_"
).
"delete"
Remove any invalid character.
"hex"
Replace all invalid characters with their hexadecimal representation.
Whitespace characters are always removed prior to the application
of the "ReplacementStyle"
. Lowercase letters following a whitespace
will be changed to uppercase.
The "Prefix"
option specifies the string pfx to add as a
prefix to the input if it begins with a digit. pfx must be a valid
variable name itself. The default prefix is "x"
.
The optional output ismodified is a logical array indicating whether the respective element in str was a valid name or not.
See also: iskeyword, isvarname, matlab.lang.makeUniqueStrings.
uniqstr =
matlab.lang.makeUniqueStrings (str)
¶uniqstr =
matlab.lang.makeUniqueStrings (str, ex)
¶uniqstr =
matlab.lang.makeUniqueStrings (str, ex, maxlength)
¶[uniqstr, ismodified] =
matlab.lang.makeUniqueStrings (…)
¶Construct a list of unique strings from a list of strings.
The input str must be a string or a cell array of strings. The output uniqstr will be of the same type.
The algorithm makes two strings unique by appending an underscore
("_"
and a numeric count to the second string.
If ex is a string or a cell array of strings, uniqstr will contain elements that are unique between themselves and with respect to ex.
If ex is an index array or a logical array for str then it selects the subset of str that are made unique. Unselected elements are not modified.
The optional input maxlength specifies the maximum length of any string in uniqstr. If an input string cannot be made unique without exceeding maxlength an error is emitted.
The optional output ismodified is a logical array indicating whether each element in str was modified to make it unique.
See also: unique, matlab.lang.makeValidName.
n =
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.
A global variable is one that may be accessed anywhere within Octave.
This is in contrast to a local variable which can only be accessed outside
of its current context if it is passed explicitly, such as by including it as a
parameter when calling a function
(fcn (local_var1, local_var2)
).
A variable is declared global by using a global
declaration statement.
The following statements are all global declarations.
global a global a b global c = 2 global d = 3 e f = 5
Note that the global
qualifier extends only to the next end-of-statement
indicator which could be a comma (‘,’), semicolon (‘;’), or newline
(‘'\n'’). For example, the following code declares one global variable,
a, and one local variable b to which the value 1 is assigned.
global a, b = 1
A global variable may only be initialized once in a global
statement.
For example, after executing the following code
global gvar = 1 global gvar = 2
the value of the global variable gvar
is 1, not 2. Issuing a
‘clear gvar’ command does not change the above behavior, but
‘clear all’ does.
It is necessary declare a variable as global within a function body in order to access the one universal variable. For example,
global x function f () x = 1; endfunction f ()
does not set the value of the global variable x
to 1. Instead,
a local variable, with name x
, is created and assigned the value of 1.
In order to change the value of the global variable x
, you must also
declare it to be global within the function body, like this
function f () global x; x = 1; endfunction
Passing a global variable in a function parameter list will make a local copy and not modify the global value. For example, given the function
function f (x) x = 0 endfunction
and the definition of x
as a global variable at the top level,
global x = 13
the expression
f (x)
will display the value of x
from inside the function as 0, but the value
of x
at the top level remains unchanged, because the function works with
a copy of its argument.
Programming Note: While global variables occasionally are the right solution to a coding problem, modern best practice discourages their use. Code which relies on global variables may behave unpredictably between different users and can be difficult to debug. This is because global variables can introduce systemic changes so that localizing a bug to a particular function, or to a particular loop within a function, becomes difficult.
tf =
isglobal (name)
¶Return true if name is a globally visible variable.
For example:
global x isglobal ("x") ⇒ 1
A variable that has been declared persistent within a function will retain its contents in memory between subsequent calls to the same function. The difference between persistent variables and global variables is that persistent variables are local in scope to a particular function and are not visible elsewhere.
The following example uses a persistent variable to create a function that prints the number of times it has been called.
function count_calls () persistent calls = 0; printf ("'count_calls' has been called %d times\n", ++calls); endfunction for i = 1:3 count_calls (); endfor -| 'count_calls' has been called 1 times -| 'count_calls' has been called 2 times -| 'count_calls' has been called 3 times
As the example shows, a variable may be declared persistent using a
persistent
declaration statement. The following statements are
all persistent declarations.
persistent a persistent a b persistent c = 2 persistent d = 3 e f = 5
The behavior of persistent variables is equivalent to the behavior of static variables in C.
One restriction for persistent variables is, that neither input nor output arguments of a function can be persistent:
function y = foo () persistent y = 0; # Not allowed! endfunction foo () -| error: can't make function parameter y persistent
Like global variables, a persistent variable may only be initialized once. For example, after executing the following code
persistent pvar = 1 persistent pvar = 2
the value of the persistent variable pvar
is 1, not 2.
If a persistent variable is declared but not initialized to a specific value, it will contain an empty matrix. So, it is also possible to initialize a persistent variable by checking whether it is empty, as the following example illustrates.
function count_calls () persistent calls; if (isempty (calls)) calls = 0; endif printf ("'count_calls' has been called %d times\n", ++calls); endfunction
This implementation behaves in exactly the same way as the previous
implementation of count_calls
.
The value of a persistent variable is kept in memory until it is
explicitly cleared. Assuming that the implementation of count_calls
is saved on disk, we get the following behavior.
for i = 1:2 count_calls (); endfor -| 'count_calls' has been called 1 times -| 'count_calls' has been called 2 times clear for i = 1:2 count_calls (); endfor -| 'count_calls' has been called 3 times -| 'count_calls' has been called 4 times clear all for i = 1:2 count_calls (); endfor -| 'count_calls' has been called 1 times -| 'count_calls' has been called 2 times clear count_calls for i = 1:2 count_calls (); endfor -| 'count_calls' has been called 1 times -| 'count_calls' has been called 2 times
That is, the persistent variable is only removed from memory when the
function containing the variable is removed. Note that if the function
definition is typed directly into the Octave prompt, the persistent
variable will be cleared by a simple clear
command as the entire
function definition will be removed from memory. If you do not want
a persistent variable to be removed from memory even if the function is
cleared, you should use the mlock
function
(see Function Locking).
When creating simple one-shot programs it can be very convenient to
see which variables are available at the prompt. The function who
and its siblings whos
and whos_line_format
will show
different information about what is in memory, as the following shows.
str = "A random string"; who -| Variables in the current scope: -| -| ans str
pattern …
¶option pattern …
¶C =
who (…)
¶List currently defined variables matching the given patterns.
Valid pattern syntax is the same as described for the clear
command.
If no patterns are supplied, all variables are listed.
By default, only variables visible in the local scope are displayed.
The following are valid options, but may not be combined.
global
List variables in the global scope rather than the current scope.
-regexp
The patterns are considered to be regular expressions when matching the
variables to display. The same pattern syntax accepted by the regexp
function is used.
-file
The next argument is treated as a filename. All variables found within the specified file are listed. No patterns are accepted when reading variables from a file.
If called as a function, return a cell array of defined variable names matching the given patterns.
pattern …
¶option pattern …
¶S =
whos ("pattern", …)
¶Provide detailed information on currently defined variables matching the given patterns.
Options and pattern syntax are the same as for the who
command.
Extended information about each variable is summarized in a table with the following default entries.
Attributes of the listed variable. Possible attributes are:
Variable in local scope
c
Variable of complex type.
f
Formal parameter (function argument).
g
Variable with global scope.
p
Persistent variable.
The name of the variable.
The logical size of the variable. A scalar is 1x1, a vector is 1xN or Nx1, a 2-D matrix is MxN.
The amount of memory currently used to store the variable.
The class of the variable. Examples include double, single, char, uint16, cell, and struct.
The table can be customized to display more or less information through
the function whos_line_format
.
If whos
is called as a function, return a struct array of defined
variable names matching the given patterns. Fields in the structure
describing each variable are: name, size, bytes, class, global, sparse,
complex, nesting, persistent.
See also: who, whos_line_format.
val =
whos_line_format ()
¶old_val =
whos_line_format (new_val)
¶old_val =
whos_line_format (new_val, "local")
¶Query or set the format string used by the command whos
.
A full format string is:
%[modifier]<command>[:width[:left-min[:balance]]];
The following command sequences are available:
%a
Prints attributes of variables (c=complex, s=sparse, f=formal parameter, g=global, p=persistent).
%b
Prints number of bytes occupied by variables.
%c
Prints class names of variables.
%e
Prints elements held by variables.
%n
Prints variable names.
%s
Prints dimensions of variables.
%t
Prints type names of variables.
Every command may also have an alignment modifier:
l
Left alignment.
r
Right alignment (default).
c
Column-aligned (only applicable to command %s).
The width
parameter is a positive integer specifying the minimum
number of columns used for printing. No maximum is needed as the field will
auto-expand as required.
The parameters left-min
and balance
are only available when
the column-aligned modifier is used with the command ‘%s’.
balance
specifies the column number within the field width which
will be aligned between entries. Numbering starts from 0 which indicates
the leftmost column. left-min
specifies the minimum field width to
the left of the specified balance column.
The default format is:
" %la:5; %ln:6; %cs:16:6:1; %rb:12; %lc:-1;\n"
When called from inside a function with the "local"
option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: whos.
Instead of displaying which variables are in memory, it is possible to determine if a given variable is available. That way it is possible to alter the behavior of a program depending on the existence of a variable. The following example illustrates this.
if (! exist ("meaning", "var")) disp ("The program has no 'meaning'"); endif
c =
exist (name)
¶c =
exist (name, type)
¶Check for the existence of name as a variable, function, file, directory, or class.
The return code c is one of
name is a variable.
name is an absolute filename, an ordinary file in Octave’s path
,
or (after appending ‘.m’) a function file in Octave’s path
.
name is a ‘.oct’ or ‘.mex’ file in Octave’s path
.
name is a built-in function.
name is a directory.
name is a classdef class.
name is a function not associated with a file (entered on the command line).
name does not exist.
If the optional argument type is supplied, check only for symbols of the specified type. Valid types are
"var"
Check only for variables.
"builtin"
Check only for built-in functions.
"dir"
Check only for directories.
"file"
Check only for files and directories.
"class"
Check only for classdef classes.
If no type is given, and there are multiple possible matches for name,
exist
will return a code according to the following priority list:
variable, built-in function, oct-file, directory, file, class.
exist
returns 2 if a regular file called name is present in
Octave’s search path. For information about other types of files not on the
search path use some combination of the functions file_in_path
and
stat
instead.
Programming Note: If name is implemented by a buggy .oct/.mex file, calling exist may cause Octave to crash. To maintain high performance, Octave trusts .oct/.mex files instead of sandboxing them.
See also: file_in_loadpath, file_in_path, dir_in_loadpath, stat.
Usually Octave will manage the memory, but sometimes it can be practical to remove variables from memory manually. This is usually needed when working with large variables that fill a substantial part of the memory. On a computer that uses the IEEE floating point format, the following program allocates a matrix that requires around 128 MB memory.
large_matrix = zeros (4000, 4000);
Since having this variable in memory might slow down other computations,
it can be necessary to remove it manually from memory. The clear
or clearvars
functions do this.
pattern …
¶options pattern …
¶Delete the names matching the given patterns thereby freeing memory.
The pattern may contain the following special characters:
?
Match any single character.
*
Match zero or more characters.
[ list ]
Match the list of characters specified by list. If the first character
is !
or ^
, match all characters except those specified by
list. For example, the pattern [a-zA-Z]
will match all lowercase
and uppercase alphabetic characters.
For example, the command
clear foo b*r
clears the name foo
and all names that begin with the letter ‘b’
and end with the letter ‘r’.
If clear
is called without any arguments, all user-defined variables
are cleared from the current workspace (i.e., local variables). Any global
variables present will no longer be visible in the current workspace, but they
will continue to exist in the global workspace. Functions are unaffected by
this form of clear
.
The following options are available in both long and short form
all, -all, -a
Clear all local and global user-defined variables, and all functions from the symbol table.
-exclusive, -x
Clear variables that do not match the following pattern.
functions, -functions, -f
Clear function names from the function symbol table. Persistent variables
will be re-initialized to their default value unless the function has been
locked in memory with mlock
.
global, -global, -g
Clear global variable names.
variables, -variables, -v
Clear local variable names.
classes, -classes, -c
Clear the class structure table and all objects.
-regexp, -r
The pattern arguments are treated as regular expressions and any matches will be cleared.
With the exception of -exclusive and -regexp, all long options can be used without the dash as well. Note that, aside from -exclusive, only one other option may appear. All options must appear before any patterns.
Programming Notes: The command clear name
only clears the variable
name when both a variable and a (shadowed) function named name
are currently defined. For example, suppose you have defined a function
foo
, and then hidden it by performing the assignment foo = 2
.
Executing the command clear foo
once will clear the variable
definition and restore the definition of foo
as a function.
Executing clear foo
a second time will clear the function definition.
When a local variable name, which is linked to a global variable, is cleared
only the local copy of the variable is removed. The global copy is untouched
and can be restored with global global_varname
. Conversely,
clear -g global_varname
will remove both the local and global
variables.
pattern …
¶-regexp pattern …
¶… -except pattern …
¶… -except -regexp pattern …
¶-global …
¶Delete the variables matching the given patterns from memory.
The pattern may contain the following special characters:
?
Match any single character.
*
Match zero or more characters.
[ list ]
Match the list of characters specified by list. If the first
character is !
or ^
, match all characters except those
specified by list. For example, the pattern [a-zA-Z]
will
match all lowercase and uppercase alphabetic characters.
If the -regexp option is given then subsequent patterns are treated as regular expressions and any matches will be cleared.
If the -except option is given then subsequent patterns select variables that will not be cleared.
If the -global option is given then all patterns will be applied to global variables rather than local variables.
When called with no arguments, clearvars
deletes all local variables.
Example Code:
Clear all variables starting with 'x'
and the specific variable
"foobar"
clearvars x* foobar
Clear the specific variable "foobar"
and use regular expressions to
clear all variables starting with 'x'
or 'y'
.
clearvars foobar -regexp ^x ^y
Clear all variables except for "foobar"
clearvars -except foobar
Clear all variables beginning with "foo"
, except for those ending
in "bar"
clearvars foo* -except -regexp bar$
()
¶Consolidate workspace memory in MATLAB.
This function is provided for compatibility, but does nothing in Octave.
See also: clear.
Information about a function or variable such as its location in the file system can also be acquired from within Octave. This is usually only useful during development of programs, and not within a program.
name …
¶-q name …
¶text =
type ("name", …)
¶Display the contents of name which may be a file, function (m-file), variable, operator, or keyword.
type
normally prepends a header line describing the category of
name such as function or variable; The -q option suppresses
this behavior.
If no output variable is used the contents are displayed on screen. Otherwise, a cell array of strings is returned, where each element corresponds to the contents of each requested function.
name …
¶Display the type of each name.
If name is defined from a function file, the full name of the file is also displayed.
dir
¶w =
what (dir)
¶List the Octave specific files in directory dir.
If dir is not specified then the current directory is used.
If a return argument is requested, the files found are returned in the structure w. The structure contains the following fields:
Full path to directory dir
Cell array of m-files
Cell array of mat files
Cell array of mex files
Cell array of oct files
Cell array of mdl files
Cell array of slx files
Cell array of p-files
Cell array of class directories (@classname/)
Cell array of package directories (+pkgname/)
Compatibility Note: Octave does not support mdl, slx, and p files.
what
will always return an empty list for these categories.
Expressions are the basic building block of statements in Octave. An expression evaluates to a value, which you can print, test, store in a variable, pass to a function, or assign a new value to a variable with an assignment operator.
An expression can serve as a statement on its own. Most other kinds of statements contain one or more expressions which specify data to be operated on. As in other languages, expressions in Octave include variables, array references, constants, and function calls, as well as combinations of these with various operators.
An index expression allows you to reference or extract selected elements of a vector, a matrix (2-D), or a higher-dimensional array.
Indices may be scalars, vectors, ranges, or the special operator ‘:’, which selects entire rows, columns, or higher-dimensional slices.
An index expression consists of a set of parentheses enclosing M expressions separated by commas. Each individual index value, or component, is used for the respective dimension of the object that it is applied to. In other words, the first index component is used for the first dimension (rows) of the object, the second index component is used for the second dimension (columns) of the object, and so on. The number of index components M defines the dimensionality of the index expression. An index with two components would be referred to as a 2-D index because it has two dimensions.
In the simplest case, 1) all components are scalars, and 2) the dimensionality of the index expression M is equal to the dimensionality of the object it is applied to. For example:
A = reshape (1:8, 2, 2, 2) # Create 3-D array A = ans(:,:,1) = 1 3 2 4 ans(:,:,2) = 5 7 6 8 A(2, 1, 2) # second row, first column of second slice # in third dimension: ans = 6
The size of the returned object in a specific dimension is equal to the number of elements in the corresponding component of the index expression. When all components are scalars, the result is a single output value. However, if any component is a vector or range then the returned values are the Cartesian product of the indices in the respective dimensions. For example:
A([1, 2], 1, 2) ≡ [A(1,1,2); A(2,1,2)] ⇒ ans = 5 6
The total number of returned values is the product of the number of elements returned for each index component. In the example above, the total is 2*1*1 = 2 elements.
Notice that the size of the returned object in a given dimension is equal to
the number of elements in the index expression for that dimension. In the code
above, the first index component ([1, 2]
) was specified as a row vector,
but its shape is unimportant. The important fact is that the component
specified two values, and hence the result must have a size of two in the first
dimension; and because the first dimension corresponds to rows, the overall
result is a column vector.
A(1, [2, 1, 1], 1) # result is a row vector: ans = [3, 1, 1] A(ones (2, 2), 1, 1) # result is a column vector: ans = [1; 1; 1; 1]
The first line demonstrates again that the size of the output in a given dimension is equal to the number of elements in the respective indexing component. In this case, the output has three elements in the second dimension (which corresponds to columns), so the result is a row vector. The example also shows how repeating entries in the index expression can be used to replicate elements in the output. The last example further proves that the shape of the indexing component is irrelevant, it is only the number of elements (2x2 = 4) which is important.
The above rules apply whenever the dimensionality of the index expression is greater than one (M > 1). However, for one-dimensional index expressions special rules apply and the shape of the output is determined by the shape of the indexing component. For example:
A([1, 2]) # result is a row vector: ans = [1, 2] A([1; 2]) # result is a column vector: ans = [1; 2]
The shape rules for A(P) are:
Note that it is permissible to use a 1-D index with a multi-dimensional object (also called linear indexing). In this case, the elements of the multi-dimensional array are taken in column-first order like Fortran. That is, the columns of the array are imagined to be stacked on top of each other to form a column vector and then the single linear index is applied to this vector.
A(5) # linear indexing into three-dimensional array: ans = 5 A(3:5) # result has shape of index component: ans = [3, 4, 5]
A colon (‘:’) may be used as an index component to select all of the elements in a specified dimension. Given the matrix,
A = [1, 2; 3, 4]
all of the following expressions are equivalent and select the first row of the matrix.
A(1, [1, 2]) # row 1, columns 1 and 2 A(1, 1:2) # row 1, columns in range 1-2 A(1, :) # row 1, all columns
When a colon is used in the special case of 1-D indexing the result is always a
column vector. Creating column vectors with a colon index is a very frequently
encountered code idiom and is faster and generally clearer than calling
reshape
for this case.
A(:) # result is column vector: ans = [1; 2; 3; 4] A(:)' # result is row vector: ans = [1, 2, 3, 4]
In index expressions the keyword end
automatically refers to the last
entry for a particular dimension. This magic index can also be used in ranges
and typically eliminates the needs to call size
or length
to
gather array bounds before indexing. For example:
A(1:end/2) # first half of A => [1, 2] A(end + 1) = 5; # append element A(end) = []; # delete element A(1:2:end) # odd elements of A => [1, 3] A(2:2:end) # even elements of A => [2, 4] A(end:-1:1) # reversal of A => [4, 3, 2, 1]
When it is necessary to extract subsets of entries out of an array whose
indices cannot be written as a Cartesian product of components, linear
indexing together with the function sub2ind
can be used. For example:
A = reshape (1:8, 2, 2, 2) # Create 3-D array A = ans(:,:,1) = 1 3 2 4 ans(:,:,2) = 5 7 6 8 A(sub2ind (size (A), [1, 2, 1], [1, 1, 2], [1, 2, 1])) ⇒ ans = [A(1, 1, 1), A(2, 1, 2), A(1, 2, 1)]
An array with ‘nd’ dimensions can be indexed by an index expression which has from 1 to ‘nd’ components. For the ordinary and most common case, the number of components ‘M’ matches the number of dimensions ‘nd’. In this case the ordinary indexing rules apply and each component corresponds to the respective dimension of the array.
However, if the number of indexing components exceeds the number of dimensions
(M > nd
) then the excess components must all be singletons
(1
). Moreover, if M < nd
, the behavior is equivalent to
reshaping the input object so as to merge the trailing nd - M
dimensions into the last index dimension M
. Thus, the result will have
the dimensionality of the index expression, and not the original object. This
is the case whenever dimensionality of the index is greater than one
(M > 1
), so that the special rules for linear indexing are not
applied. This is easiest to understand with an example:
A = reshape (1:8, 2, 2, 2) # Create 3-D array A = ans(:,:,1) = 1 3 2 4 ans(:,:,2) = 5 7 6 8 ## 2-D indexing causes third dimension to be merged into second dimension. ## Equivalent array for indexing, Atmp, is now 2x4. Atmp = reshape (A, 2, 4) Atmp = 1 3 5 7 2 4 6 8 A(2,1) # Reshape to 2x4 matrix, second entry of first column: ans = 2 A(2,4) # Reshape to 2x4 matrix, second entry of fourth column: ans = 8 A(:,:) # Reshape to 2x4 matrix, select all rows & columns, ans = Atmp
Note here the elegant use of the double colon to replace the call to the
reshape
function.
Another advanced use of linear indexing is to create arrays filled with a single value. This can be done by using an index of ones on a scalar value. The result is an object with the dimensions of the index expression and every element equal to the original scalar. For example, the following statements
a = 13; a(ones (1, 4))
produce a row vector whose four elements are all equal to 13.
Similarly, by indexing a scalar with two vectors of ones it is possible to create a matrix. The following statements
a = 13; a(ones (1, 2), ones (1, 3))
create a 2x3 matrix with all elements equal to 13. This could also have been written as
13(ones (2, 3))
It is more efficient to use indexing rather than the code construction
scalar * ones (M, N, …)
because it avoids the unnecessary
multiplication operation. Moreover, multiplication may not be defined for the
object to be replicated whereas indexing an array is always defined. The
following code shows how to create a 2x3 cell array from a base unit which is
not itself a scalar.
{"Hello"}(ones (2, 3))
It should be noted that ones (1, n)
(a row vector of ones) results in a
range object (with zero increment). A range is stored internally as a starting
value, increment, end value, and total number of values; hence, it is more
efficient for storage than a vector or matrix of ones whenever the number of
elements is greater than 4. In particular, when ‘r’ is a row vector, the
expressions
r(ones (1, n), :)
r(ones (n, 1), :)
will produce identical results, but the first one will be significantly faster, at least for ‘r’ and ‘n’ large enough. In the first case the index is held in compressed form as a range which allows Octave to choose a more efficient algorithm to handle the expression.
A general recommendation for users unfamiliar with these techniques is to use
the function repmat
for replicating smaller arrays into bigger ones,
which uses such tricks.
A second use of indexing is to speed up code. Indexing is a fast operation and judicious use of it can reduce the requirement for looping over individual array elements, which is a slow operation.
Consider the following example which creates a 10-element row vector a containing the values a(i) = sqrt (i).
for i = 1:10 a(i) = sqrt (i); endfor
It is quite inefficient to create a vector using a loop like this. In this case, it would have been much more efficient to use the expression
a = sqrt (1:10);
which avoids the loop entirely.
In cases where a loop cannot be avoided, or a number of values must be combined
to form a larger matrix, it is generally faster to set the size of the matrix
first (pre-allocate storage), and then insert elements using indexing commands.
For example, given a matrix a
,
[nr, nc] = size (a); x = zeros (nr, n * nc); for i = 1:n x(:,(i-1)*nc+1:i*nc) = a; endfor
is considerably faster than
x = a; for i = 1:n-1 x = [x, a]; endfor
because Octave does not have to repeatedly resize the intermediate result.
ind =
sub2ind (dims, i, j)
¶ind =
sub2ind (dims, s1, s2, …, sN)
¶Convert subscripts to linear indices.
The input dims is a dimension vector where each element is the size of
the array in the respective dimension (see size
). The
remaining inputs are scalars or vectors of subscripts to be converted.
The output vector ind contains the converted linear indices.
Background: Array elements can be specified either by a linear index which
starts at 1 and runs through the number of elements in the array, or they may
be specified with subscripts for the row, column, page, etc. The functions
ind2sub
and sub2ind
interconvert between the two forms.
The linear index traverses dimension 1 (rows), then dimension 2 (columns), then dimension 3 (pages), etc. until it has numbered all of the elements. Consider the following 3-by-3 matrices:
[(1,1), (1,2), (1,3)] [1, 4, 7] [(2,1), (2,2), (2,3)] ==> [2, 5, 8] [(3,1), (3,2), (3,3)] [3, 6, 9]
The left matrix contains the subscript tuples for each matrix element. The right matrix shows the linear indices for the same matrix.
The following example shows how to convert the two-dimensional indices
(2,1)
and (2,3)
of a 3-by-3 matrix to linear indices with a
single call to sub2ind
.
s1 = [2, 2]; s2 = [1, 3]; ind = sub2ind ([3, 3], s1, s2) ⇒ ind = 2 8
[s1, s2, …, sN] =
ind2sub (dims, ind)
¶Convert linear indices to subscripts.
The input dims is a dimension vector where each element is the size of
the array in the respective dimension (see size
). The
second input ind contains linear indices to be converted.
The outputs s1, …, sN contain the converted subscripts.
Background: Array elements can be specified either by a linear index which
starts at 1 and runs through the number of elements in the array, or they may
be specified with subscripts for the row, column, page, etc. The functions
ind2sub
and sub2ind
interconvert between the two forms.
The linear index traverses dimension 1 (rows), then dimension 2 (columns), then dimension 3 (pages), etc. until it has numbered all of the elements. Consider the following 3-by-3 matrices:
[1, 4, 7] [(1,1), (1,2), (1,3)] [2, 5, 8] ==> [(2,1), (2,2), (2,3)] [3, 6, 9] [(3,1), (3,2), (3,3)]
The left matrix contains the linear indices for each matrix element. The right matrix shows the subscript tuples for the same matrix.
The following example shows how to convert the linear indices 2
and
8
to appropriate subscripts of a 3-by-3 matrix.
ind = [2, 8]; [r, c] = ind2sub ([3, 3], ind) ⇒ r = 2 2 ⇒ c = 1 3
If the number of output subscripts exceeds the number of dimensions, the
exceeded dimensions are set to 1
. On the other hand, if fewer
subscripts than dimensions are provided, the exceeding dimensions are merged
into the final requested dimension. For clarity, consider the following
examples:
ind = [2, 8]; dims = [3, 3]; ## same as dims = [3, 3, 1] [r, c, s] = ind2sub (dims, ind) ⇒ r = 2 2 ⇒ c = 1 3 ⇒ s = 1 1 ## same as dims = [9] r = ind2sub (dims, ind) ⇒ r = 2 8
tf =
isindex (ind)
¶tf =
isindex (ind, n)
¶Return true if ind is a valid index.
Valid indices are either positive integers (although possibly of real data type), or logical arrays.
If present, n specifies the maximum extent of the dimension to be indexed. When possible the internal result is cached so that subsequent indexing using ind will not perform the check again.
Implementation Note: Strings are first converted to double values before the checks for valid indices are made. Unless a string contains the NULL character "\0", it will always be a valid index.
A function is a name for a particular calculation. Because it has
a name, you can ask for it by name at any point in the program. For
example, the function sqrt
computes the square root of a number.
A fixed set of functions are built-in, which means they are
available in every Octave program. The sqrt
function is one of
these. In addition, you can define your own functions.
See Functions and Scripts, for information about how to do this.
The way to use a function is with a function call expression, which consists of the function name followed by a list of arguments in parentheses. The arguments are expressions which give the raw materials for the calculation that the function will do. When there is more than one argument, they are separated by commas. If there are no arguments, you can omit the parentheses, but it is a good idea to include them anyway, to clearly indicate that a function call was intended. Here are some examples:
sqrt (x^2 + y^2) # One argument ones (n, m) # Two arguments rand () # No arguments
Each function expects a particular number of arguments. For example, the
sqrt
function must be called with a single argument, the number
to take the square root of:
sqrt (argument)
Some of the built-in functions take a variable number of arguments, depending on the particular usage, and their behavior is different depending on the number of arguments supplied.
Like every other expression, the function call has a value, which is
computed by the function based on the arguments you give it. In this
example, the value of sqrt (argument)
is the square root of
the argument. A function can also have side effects, such as assigning
the values of certain variables or doing input or output operations.
Unlike most languages, functions in Octave may return multiple values. For example, the following statement
[u, s, v] = svd (a)
computes the singular value decomposition of the matrix a
and
assigns the three result matrices to u
, s
, and v
.
The left side of a multiple assignment expression is itself a list of expressions, that is, a list of variable names potentially qualified by index expressions. See also Index Expressions, and Assignment Expressions.
In Octave, unlike Fortran, function arguments are passed by value, which means that each argument in a function call is evaluated and assigned to a temporary location in memory before being passed to the function. There is currently no way to specify that a function parameter should be passed by reference instead of by value. This means that it is impossible to directly alter the value of a function parameter in the calling function. It can only change the local copy within the function body. For example, the function
function f (x, n) while (n-- > 0) disp (x); endwhile endfunction
displays the value of the first argument n times. In this function, the variable n is used as a temporary variable without having to worry that its value might also change in the calling function. Call by value is also useful because it is always possible to pass constants for any function parameter without first having to determine that the function will not attempt to modify the parameter.
The caller may use a variable as the expression for the argument, but the called function does not know this: it only knows what value the argument had. For example, given a function called as
foo = "bar"; fcn (foo)
you should not think of the argument as being “the variable
foo
.” Instead, think of the argument as the string value,
"bar"
.
Even though Octave uses pass-by-value semantics for function arguments, values are not copied unnecessarily. For example,
x = rand (1000); f (x);
does not actually force two 1000 by 1000 element matrices to exist
unless the function f
modifies the value of its
argument. Then Octave must create a copy to avoid changing the
value outside the scope of the function f
, or attempting (and
probably failing!) to modify the value of a constant or the value of a
temporary result.
With some restrictions3, recursive function calls are allowed. A recursive function is one which calls itself, either directly or indirectly. For example, here is an inefficient4 way to compute the factorial of a given integer:
function retval = fact (n) if (n > 0) retval = n * fact (n-1); else retval = 1; endif endfunction
This function is recursive because it calls itself directly. It eventually terminates because each time it calls itself, it uses an argument that is one less than was used for the previous call. Once the argument is no longer greater than zero, it does not call itself, and the recursion ends.
The function max_recursion_depth
may be used to specify a limit
to the recursion depth and prevents Octave from recursing infinitely.
Similarly, the function max_stack_depth
may be used to specify
limit to the depth of function calls, whether recursive or not. These
limits help prevent stack overflow on the computer Octave is running on,
so that instead of exiting with a signal, the interpreter will throw an
error and return to the command prompt.
val =
max_recursion_depth ()
¶old_val =
max_recursion_depth (new_val)
¶old_val =
max_recursion_depth (new_val, "local")
¶Query or set the internal limit on the number of times a function may be called recursively.
If the limit is exceeded, an error message is printed and control returns to the top level.
When called from inside a function with the "local"
option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: max_stack_depth.
val =
max_stack_depth ()
¶old_val =
max_stack_depth (new_val)
¶old_val =
max_stack_depth (new_val, "local")
¶Query or set the internal limit on the number of times a function may be called recursively.
If the limit is exceeded, an error message is printed and control returns to the top level.
When called from inside a function with the "local"
option, the
variable is changed locally for the function and any subroutines it calls.
The original variable value is restored when exiting the function.
See also: max_recursion_depth.
A function may be abstracted and referenced via a function handle acquired using the special operator ‘@’. For example,
f = @plus; f (2, 2) ⇒ 4
is equivalent to calling plus (2, 2)
directly. Beyond abstraction for
general programming, function handles find use in callback methods for figures
and graphics by adding listeners to properties or assigning pre-existing
actions, such as in the following example:
function mydeletefcn (h, ~, msg) printf (msg); endfunction sombrero; set (gcf, "deletefcn", {@mydeletefcn, "Bye!\n"}); close;
The above will print "Bye!"
to the terminal upon the closing
(deleting) of the figure. There are many graphics property actions for which
a callback function may be assigned, including, buttondownfcn
,
windowscrollwheelfcn
, createfcn
, deletefcn
,
keypressfcn
, etc.
Note that the ‘@’ character also plays a role in defining class functions, i.e., methods, but not as a syntactical element. Rather it begins a directory name containing methods for a class that shares the directory name sans the ‘@’ character. See Object Oriented Programming.
The following arithmetic operators are available, and work on scalars and matrices. The element-by-element operators and functions broadcast (see Broadcasting).
Addition (always works element by element). If both operands are matrices, the number of rows and columns must both agree, or they must be broadcastable to the same shape.
Subtraction (always works element by element). If both operands are matrices, the number of rows and columns of both must agree, or they must be broadcastable to the same shape.
Matrix multiplication. The number of columns of x must agree with the number of rows of y.
Element-by-element multiplication. If both operands are matrices, the number of rows and columns must both agree, or they must be broadcastable to the same shape.
Right division. This is conceptually equivalent to the expression
(inv (y') * x')'
but it is computed without forming the inverse of y’.
If the system is not square, or if the coefficient matrix is singular, a minimum norm solution is computed.
Element-by-element right division.
Left division. This is conceptually equivalent to the expression
inv (x) * y
but it is computed without forming the inverse of x.
If the system is not square, or if the coefficient matrix is singular, a minimum norm solution is computed.
Element-by-element left division. Each element of y is divided by each corresponding element of x.
Power operator. If x and y are both scalars, this operator returns x raised to the power y. If x is a scalar and y is a square matrix, the result is computed using an eigenvalue expansion. If x is a square matrix, the result is computed by repeated multiplication if y is an integer, and by an eigenvalue expansion if y is not an integer. An error results if both x and y are matrices.
The implementation of this operator needs to be improved.
Element-by-element power operator. If both operands are matrices, the
number of rows and columns must both agree, or they must be
broadcastable to the same shape. If several complex results are
possible, the one with smallest non-negative argument (angle) is taken.
This rule may return a complex root even when a real root is also possible.
Use realpow
, realsqrt
, cbrt
, or nthroot
if a
real result is preferred.
Negation.
Unary plus. This operator has no effect on the operand.
Complex conjugate transpose. For real arguments, this operator is the same as the transpose operator. For complex arguments, this operator is equivalent to the expression
conj (x.')
Transpose.
Note that because Octave’s element-by-element operators begin with a ‘.’, there is a possible ambiguity for statements like
1./m
because the period could be interpreted either as part of the constant or as part of the operator. To resolve this conflict, Octave treats the expression as if you had typed
(1) ./ m
and not
(1.) / m
Although this is inconsistent with the normal behavior of Octave’s lexer, which usually prefers to break the input into tokens by preferring the longest possible match at any given point, it is more useful in this case.
Note also that some combinations of binary operators and whitespace can create apparent ambiguities with the Command Syntax form of calling functions. See Command Syntax and Function Syntax for a description of how Octave treats that syntax.
B =
ctranspose (A)
¶Return the complex conjugate transpose of A.
This function and A'
are equivalent.
See also: transpose.
y =
pagectranspose (A)
¶Return the page-wise complex conjugate transpose of the N-dimensional array A.
This is equivalent to A(:,:, k)'
for each page k.
See also: pagetranspose, ctranspose, permute.
C =
ldivide (A, B)
¶Return the element-by-element left division of A and B.
This function and A .\ B
are
equivalent.
C =
mldivide (A, B)
¶Return the matrix left division of A and B.
This function and A \ B
are equivalent.
If the system is not square, or if the coefficient matrix is singular, a minimum norm solution is computed.
C =
mpower (A, B)
¶Return the matrix power operation of A raised to the B power.
This function and A ^ B
are equivalent.
C =
mrdivide (A, B)
¶Return the matrix right division of A and B.
This function and A / B
are equivalent.
If the system is not square, or if the coefficient matrix is singular, a minimum norm solution is computed.
C =
mtimes (A, B)
¶C =
mtimes (A1, A2, …)
¶Return the matrix multiplication product of inputs.
This function and A * B
are equivalent.
If more arguments are given, the multiplication is applied
cumulatively from left to right:
(…((A1 * A2) * A3) * …)
See also: times, plus, minus, rdivide, mrdivide, mldivide, mpower.
C =
plus (A, B)
¶C =
plus (A1, A2, …)
¶This function and A + B
are equivalent.
If more arguments are given, the summation is applied cumulatively from left to right:
(…((A1 + A2) + A3) + …)
C =
power (A, B)
¶Return the element-by-element operation of A raised to the B power.
This function and A .^ B
are equivalent.
If several complex results are possible, returns the one with smallest
non-negative argument (angle). Use realpow
, realsqrt
,
cbrt
, or nthroot
if a real result is preferred.
C =
rdivide (A, B)
¶Return the element-by-element right division of A and B.
This function and A ./ B
are equivalent.
C =
times (A, B)
¶C =
times (A1, A2, …)
¶Return the element-by-element multiplication product of inputs.
This function and A .* B
are equivalent.
If more arguments are given, the multiplication is applied
cumulatively from left to right:
(…((A1 .* A2) .* A3) .* …)
B =
transpose (A)
¶Return the transpose of A.
This function and A.'
are equivalent.
See also: ctranspose.
B =
pagetranspose (A)
¶Return the page-wise transpose of the N-dimensional array A.
This is equivalent to A(:,:, k).'
for each page
k.
See also: pagectranspose, transpose, permute.
Comparison operators compare numeric values for relationships such as equality. They are written using relational operators.
All of Octave’s comparison operators return a value of 1 if the comparison is true, or 0 if it is false. For matrix values, they all work on an element-by-element basis. Broadcasting rules apply. See Broadcasting. For example:
[1, 2; 3, 4] == [1, 3; 2, 4] ⇒ 1 0 0 1
According to broadcasting rules, if one operand is a scalar and the other is a matrix, the scalar is compared to each element of the matrix in turn, and the result is the same size as the matrix.
x < y
¶True if x is less than y.
x <= y
¶True if x is less than or equal to y.
x == y
¶True if x is equal to y.
x >= y
¶True if x is greater than or equal to y.
x > y
¶True if x is greater than y.
x != y
¶x ~= y
True if x is not equal to y.
For complex numbers, the following ordering is defined: z1 < z2 if and only if
abs (z1) < abs (z2) || (abs (z1) == abs (z2) && arg (z1) < arg (z2))
This is consistent with the ordering used by max, min and sort, but is not consistent with MATLAB, which only compares the real parts.
String comparisons may also be performed with the strcmp
function, not with the comparison operators listed above.
See Strings.
TF =
eq (A, B)
¶Return true if the two inputs are equal.
This function is equivalent to A == B
.
tf =
isequaln (x1, x2, …)
¶Return true if all of x1, x2, … are equal under the additional assumption that NaN == NaN (no comparison of NaN placeholders in dataset).
See also: isequal.
TF =
ne (A, B)
¶Return true if the two inputs are not equal.
This function is equivalent to A != B
.
An element-by-element boolean expression is a combination of comparison expressions using the boolean operators “or” (‘|’), “and” (‘&’), and “not” (‘!’), along with parentheses to control nesting. The truth of the boolean expression is computed by combining the truth values of the corresponding elements of the component expressions. A value is considered to be false if it is zero, and true otherwise.
Element-by-element boolean expressions can be used wherever comparison
expressions can be used. They can be used in if
and while
statements. However, a matrix value used as the condition in an
if
or while
statement is only true if all of its
elements are nonzero.
Like comparison operations, each element of an element-by-element boolean expression also has a numeric value (1 if true, 0 if false) that comes into play if the result of the boolean expression is stored in a variable, or used in arithmetic.
Here are descriptions of the three element-by-element boolean operators.
boolean1 & boolean2
¶Elements of the result are true if both corresponding elements of boolean1 and boolean2 are true.
boolean1 | boolean2
¶Elements of the result are true if either of the corresponding elements of boolean1 or boolean2 is true.
! boolean
¶~ boolean
Each element of the result is true if the corresponding element of boolean is false.
These operators work on an element-by-element basis. For example, the expression
[1, 0; 0, 1] & [1, 0; 2, 3]
returns a two by two identity matrix.
For the binary operators, broadcasting rules apply. See Broadcasting. In particular, if one of the operands is a scalar and the other a matrix, the operator is applied to the scalar and each element of the matrix.
For the binary element-by-element boolean operators, both subexpressions boolean1 and boolean2 are evaluated before computing the result. This can make a difference when the expressions have side effects. For example, in the expression
a & b++
the value of the variable b is incremented even if the variable a is zero.
This behavior is necessary for the boolean operators to work as described for matrix-valued operands.
TF =
and (x, y)
¶TF =
and (x1, x2, …)
¶Return the logical AND of x and y.
This function is equivalent to the operator syntax
x & y
. If more than two arguments are given, the
logical AND is applied cumulatively from left to right:
(…((x1 & x2) & x3) & …)
z =
not (x)
¶Return the logical NOT of x.
This function is equivalent to the operator syntax ! x
.
TF =
or (x, y)
¶TF =
or (x1, x2, …)
¶Return the logical OR of x and y.
This function is equivalent to the operator syntax
x | y
. If more than two arguments are given, the
logical OR is applied cumulatively from left to right:
(…((x1 | x2) | x3) | …)
Combined with the implicit conversion to scalar values in if
and
while
conditions, Octave’s element-by-element boolean operators
are often sufficient for performing most logical operations. However,
it is sometimes desirable to stop evaluating a boolean expression as
soon as the overall truth value can be determined. Octave’s
short-circuit boolean operators work this way.
boolean1 && boolean2
¶The expression boolean1 is evaluated and converted to a scalar using
the equivalent of the operation all (boolean1(:))
. If
boolean1 is not a logical value, it is considered true if its value
is nonzero, and false if its value is zero. If boolean1 is an array,
it is considered true only if it is non-empty and all elements are
non-zero. If boolean1 evaluates to false, the result of the overall
expression is false. If it is true, the expression boolean2 is
evaluated in the same way as boolean1. If it is true, the result of
the overall expression is true. Otherwise the result of the overall
expression is false.
Warning: the one exception to the equivalence with evaluating
all (boolean1(:))
is when boolean1
an the empty array.
For MATLAB compatibility, the truth value of an empty array is always
false
so [] && true
evaluates to false
even though
all ([])
is true
.
boolean1 || boolean2
¶The expression boolean1 is evaluated and converted to a scalar using
the equivalent of the operation all (boolean1(:))
. If
boolean1 is not a logical value, it is considered true if its value
is nonzero, and false if its value is zero. If boolean1 is an array,
it is considered true only if it is non-empty and all elements are
non-zero. If boolean1 evaluates to true, the result of the overall
expression is true. If it is false, the expression boolean2 is
evaluated in the same way as boolean1. If it is true, the result of
the overall expression is true. Otherwise the result of the overall
expression is false.
Warning: the truth value of an empty matrix is always
false
, see the previous list item for details.
The fact that both operands may not be evaluated before determining the overall truth value of the expression can be important. For example, in the expression
a && b++
the value of the variable b is only incremented if the variable a is nonzero.
This can be used to write somewhat more concise code. For example, it is possible write
function f (a, b, c) if (nargin > 2 && ischar (c)) …
instead of having to use two if
statements to avoid attempting to
evaluate an argument that doesn’t exist. For example, without the
short-circuit feature, it would be necessary to write
function f (a, b, c) if (nargin > 2) if (ischar (c)) …
Writing
function f (a, b, c) if (nargin > 2 & ischar (c)) …
would result in an error if f
were called with one or two
arguments because Octave would be forced to try to evaluate both of the
operands for the operator ‘&’.
MATLAB has special behavior that allows the operators ‘&’ and
‘|’ to short-circuit when used in the truth expression for if
and while
statements. Octave behaves the same way for
compatibility, however, the use of the ‘&’ and ‘|’ operators in
this way is strongly discouraged and a warning will be issued. Instead,
you should use the ‘&&’ and ‘||’ operators that always have
short-circuit behavior.
Finally, the ternary operator (?:) is not supported in Octave. If
short-circuiting is not important, it can be replaced by the ifelse
function.
M =
merge (mask, tval, fval)
¶M =
ifelse (mask, tval, fval)
¶Merge elements of true_val and false_val, depending on the value of mask.
If mask is a logical scalar, the other two arguments can be arbitrary values. Otherwise, mask must be a logical array, and tval, fval should be arrays of matching class, or cell arrays. In the scalar mask case, tval is returned if mask is true, otherwise fval is returned.
In the array mask case, both tval and fval must be either scalars or arrays with dimensions equal to mask. The result is constructed as follows:
result(mask) = tval(mask); result(! mask) = fval(! mask);
mask can also be arbitrary numeric type, in which case it is first converted to logical.
An assignment is an expression that stores a new value into a
variable. For example, the following expression assigns the value 1 to
the variable z
:
z = 1
After this expression is executed, the variable z
has the value 1.
Whatever old value z
had before the assignment is forgotten.
The ‘=’ sign is called an assignment operator.
Assignments can store string values also. For example, the following
expression would store the value "this food is good"
in the
variable message
:
thing = "food" predicate = "good" message = [ "this " , thing , " is " , predicate ]
(This also illustrates concatenation of strings.)
Most operators (addition, concatenation, and so on) have no effect except to compute a value. If you ignore the value, you might as well not use the operator. An assignment operator is different. It does produce a value, but even if you ignore the value, the assignment still makes itself felt through the alteration of the variable. We call this a side effect.
The left-hand operand of an assignment need not be a variable (see Variables). It can also be an element of a matrix (see Index Expressions) or a list of return values (see Calling Functions). These are all called lvalues, which means they can appear on the left-hand side of an assignment operator. The right-hand operand may be any expression. It produces the new value which the assignment stores in the specified variable, matrix element, or list of return values.
It is important to note that variables do not have permanent types.
The type of a variable is simply the type of whatever value it happens
to hold at the moment. In the following program fragment, the variable
foo
has a numeric value at first, and a string value later on:
octave:13> foo = 1 foo = 1 octave:13> foo = "bar" foo = bar
When the second assignment gives foo
a string value, the fact that
it previously had a numeric value is forgotten.
Assignment of a scalar to an indexed matrix sets all of the elements
that are referenced by the indices to the scalar value. For example, if
a
is a matrix with at least two columns,
a(:, 2) = 5
sets all the elements in the second column of a
to 5.
Assigning an empty matrix ‘[]’ works in most cases to allow you to delete rows or columns of matrices and vectors. See Empty Matrices. For example, given a 4 by 5 matrix A, the assignment
A (3, :) = []
deletes the third row of A, and the assignment
A (:, 1:2:5) = []
deletes the first, third, and fifth columns.
An assignment is an expression, so it has a value. Thus, z = 1
as an expression has the value 1. One consequence of this is that you
can write multiple assignments together:
x = y = z = 0
stores the value 0 in all three variables. It does this because the
value of z = 0
, which is 0, is stored into y
, and then
the value of y = z = 0
, which is 0, is stored into x
.
This is also true of assignments to lists of values, so the following is a valid expression
[a, b, c] = [u, s, v] = svd (a)
that is exactly equivalent to
[u, s, v] = svd (a) a = u b = s c = v
In expressions like this, the number of values in each part of the expression need not match. For example, the expression
[a, b] = [u, s, v] = svd (a)
is equivalent to
[u, s, v] = svd (a) a = u b = s
The number of values on the left side of the expression can, however, not exceed the number of values on the right side. For example, the following will produce an error.
[a, b, c, d] = [u, s, v] = svd (a); -| error: element number 4 undefined in return list
The symbol ~
may be used as a placeholder in the list of lvalues,
indicating that the corresponding return value should be ignored and not stored
anywhere:
[~, s, v] = svd (a);
This is cleaner and more memory efficient than using a dummy variable.
The nargout
value for the right-hand side expression is not affected.
If the assignment is used as an expression, the return value is a
comma-separated list with the ignored values dropped.
A very common programming pattern is to increment an existing variable with a given value, like this
a = a + 2;
This can be written in a clearer and more condensed form using the
+=
operator
a += 2;
Similar operators also exist for subtraction (-=
),
multiplication (*=
), and division (/=
). An expression
of the form
expr1 op= expr2
is evaluated as
expr1 = (expr1) op (expr2)
where op can be either +
, -
, *
, or /
,
as long as expr2 is a simple expression with no side effects. If
expr2 also contains an assignment operator, then this expression
is evaluated as
temp = expr2 expr1 = (expr1) op temp
where temp is a placeholder temporary value storing the computed result of evaluating expr2. So, the expression
a *= b+1
is evaluated as
a = a * (b+1)
and not
a = a * b + 1
You can use an assignment anywhere an expression is called for. For
example, it is valid to write x != (y = 1)
to set y
to 1
and then test whether x
equals 1. But this style tends to make
programs hard to read. Except in a one-shot program, you should rewrite
it to get rid of such nesting of assignments. This is never very hard.
Increment operators increase or decrease the value of a variable by 1. The operator to increment a variable is written as ‘++’. It may be used to increment a variable either before or after taking its value.
For example, to pre-increment the variable x, you would write
++x
. This would add one to x and then return the new
value of x as the result of the expression. It is exactly the
same as the expression x = x + 1
.
To post-increment a variable x, you would write x++
.
This adds one to the variable x, but returns the value that
x had prior to incrementing it. For example, if x is equal
to 2, the result of the expression x++
is 2, and the new
value of x is 3.
For matrix and vector arguments, the increment and decrement operators work on each element of the operand.
The increment and decrement operators must "hug" their corresponding variable. That means, no white spaces are allowed between these operators and the variable they affect.
Here is a list of all the increment and decrement expressions.
++x
¶This expression increments the variable x. The value of the
expression is the new value of x. It is equivalent to the
expression x = x + 1
.
--x
¶This expression decrements the variable x. The value of the
expression is the new value of x. It is equivalent to the
expression x = x - 1
.
x++
¶This expression causes the variable x to be incremented. The value of the expression is the old value of x.
x--
¶This expression causes the variable x to be decremented. The value of the expression is the old value of x.
Operator precedence determines how operators are grouped, when
different operators appear close by in one expression. For example,
‘*’ has higher precedence than ‘+’. Thus, the expression
a + b * c
means to multiply b
and c
, and then add
a
to the product (i.e., a + (b * c)
).
You can overrule the precedence of the operators by using parentheses. You can think of the precedence rules as saying where the parentheses are assumed if you do not write parentheses yourself. In fact, it is wise to use parentheses whenever you have an unusual combination of operators, because other people who read the program may not remember what the precedence is in this case. You might forget as well, and then you too could make a mistake. Explicit parentheses will help prevent any such mistake.
When operators of equal precedence are used together, the leftmost
operator groups first, except for the assignment operators, which group
in the opposite order. Thus, the expression a - b + c
groups as
(a - b) + c
, but the expression a = b = c
groups as
a = (b = c)
.
The precedence of prefix unary operators is important when another
operator follows the operand. For example, -x^2
means
-(x^2)
, because ‘-’ has lower precedence than ‘^’.
Here is a table of the operators in Octave, in order of decreasing precedence. Unless noted, all operators group left to right.
function call and array indexing, cell array indexing, and structure element indexing
‘()’ ‘{}’ ‘.’
postfix increment, and postfix decrement
‘++’ ‘--’
These operators group right to left.
transpose and exponentiation
‘'’ ‘.'’ ‘^’ ‘.^’
unary plus, unary minus, prefix increment, prefix decrement, and logical "not"
‘+’ ‘-’ ‘++’ ‘--’ ‘~’ ‘!’
multiply and divide
‘*’ ‘/’ ‘\’ ‘.\’ ‘.*’ ‘./’
add, subtract
‘+’ ‘-’
colon
‘:’
relational
‘<’ ‘<=’ ‘==’ ‘>=’ ‘>’ ‘!=’ ‘~=’
element-wise "and"
‘&’
element-wise "or"
‘|’
logical "and"
‘&&’
logical "or"
‘||’
assignment
‘=’ ‘+=’ ‘-=’ ‘*=’ ‘/=’ ‘\=’ ‘^=’ ‘.*=’ ‘./=’ ‘.\=’ ‘.^=’ ‘|=’ ‘&=’
These operators group right to left.
Normally, you evaluate expressions simply by typing them at the Octave prompt, or by asking Octave to interpret commands that you have saved in a file.
Sometimes, you may find it necessary to evaluate an expression that has
been computed and stored in a string, which is exactly what the
eval
function lets you do.
(try)
¶(try, catch)
¶Parse the string try and evaluate it as if it were an Octave program.
If execution fails, evaluate the optional string catch.
The string try is evaluated in the current context, so any results
remain available after eval
returns.
The following example creates the variable A with the approximate value of 3.1416 in the current workspace.
eval ("A = acos(-1);");
If an error occurs during the evaluation of try then the catch string is evaluated, as the following example shows:
eval ('error ("This is a bad example");', 'printf ("This error occurred:\n%s\n", lasterr ());'); -| This error occurred: This is a bad example
Programming Note: if you are only using eval
as an error-capturing
mechanism, rather than for the execution of arbitrary code strings,
Consider using try/catch blocks or unwind_protect/unwind_protect_cleanup
blocks instead. These techniques have higher performance and don’t
introduce the security considerations that the evaluation of arbitrary code
does.
The evalc
function additionally captures any console output
produced by the evaluated expression.
s =
evalc (try)
¶s =
evalc (try, catch)
¶Parse and evaluate the string try as if it were an Octave program, while capturing the output into the return variable s.
If execution fails, evaluate the optional string catch.
This function behaves like eval
, but any output or warning messages
which would normally be written to the console are captured and returned in
the string s.
The diary
is disabled during the execution of this function. When
system
is used, any output produced by external programs is
not captured, unless their output is captured by the system
function itself.
s = evalc ("t = 42"), t ⇒ s = t = 42 ⇒ t = 42
The feval
function allows you to call a function from a string
containing its name. This is useful when writing a function that needs to
call user-supplied functions. The feval
function takes the name
of the function to call as its first argument, and the remaining
arguments are given to the function.
The following example is a simple-minded function using feval
that finds the root of a user-supplied function of one variable using
Newton’s method.
function result = newtroot (fname, x) # usage: newtroot (fname, x) # # fname : a string naming a function f(x). # x : initial guess delta = tol = sqrt (eps); maxit = 200; fx = feval (fname, x); for i = 1:maxit if (abs (fx) < tol) result = x; return; else fx_new = feval (fname, x + delta); deriv = (fx_new - fx) / delta; x = x - fx / deriv; fx = fx_new; endif endfor result = x; endfunction
Note that this is only meant to be an example of calling user-supplied
functions and should not be taken too seriously. In addition to using a
more robust algorithm, any serious code would check the number and type
of all the arguments, ensure that the supplied function really was a
function, etc. See Predicates for Numeric Objects,
for a list of predicates for numeric objects, and see Status of Variables, for a description of the exist
function.
(name, …)
¶Evaluate the function named name.
Any arguments after the first are passed as inputs to the named function. For example,
feval ("acos", -1) ⇒ 3.1416
calls the function acos
with the argument ‘-1’.
The function feval
can also be used with function handles of any sort
(see Function Handles). Historically, feval
was the only way to
call user-supplied functions in strings, but function handles are now
preferred due to the cleaner syntax they offer. For example,
f = @exp; feval (f, 1) ⇒ 2.7183 f (1) ⇒ 2.7183
are equivalent ways to call the function referred to by f. If it
cannot be predicted beforehand whether f is a function handle,
function name in a string, or inline function then feval
can be used
instead.
A similar function run
exists for calling user script files, that
are not necessarily on the user path
script
¶("script")
¶Run script in the current workspace.
Scripts which reside in directories specified in Octave’s load path, and
which end with the extension .m, can be run simply by typing
their name. For scripts not located on the load path, use run
.
The filename script can be a bare, fully qualified, or relative filename and with or without a file extension. If no extension is specified, Octave will first search for a script with the .m extension before falling back to the script name without an extension.
Implementation Note: If script includes a path component, then
run
first changes the working directory to the directory where
script is found. Next, the script is executed. Finally, run
returns to the original working directory unless script has
specifically changed directories.
Before you evaluate an expression you need to substitute
the values of the variables used in the expression. These
are stored in the symbol table. Whenever the interpreter
starts a new function it saves the current symbol table
and creates a new one, initializing it with the list of
function parameters and a couple of predefined variables
such as nargin
. Expressions inside the function use the
new symbol table.
Sometimes you want to write a function so that when you call it, it modifies variables in your own context. This allows you to use a pass-by-name style of function, which is similar to using a pointer in programming languages such as C.
Consider how you might write save
and load
as
m-files. For example:
function create_data x = linspace (0, 10, 10); y = sin (x); save mydata x y endfunction
With evalin
, you could write save
as follows:
function save (file, name1, name2) f = open_save_file (file); save_var (f, name1, evalin ("caller", name1)); save_var (f, name2, evalin ("caller", name2)); endfunction
Here, ‘caller’ is the create_data
function and name1
is the string "x"
, which evaluates simply as the value of x
.
You later want to load the values back from mydata
in a different context:
function process_data load mydata … do work … endfunction
With assignin
, you could write load
as follows:
function load (file) f = open_load_file (file); [name, val] = load_var (f); assignin ("caller", name, val); [name, val] = load_var (f); assignin ("caller", name, val); endfunction
Here, ‘caller’ is the process_data
function.
You can set and use variables at the command prompt using the context ‘base’ rather than ‘caller’.
These functions are rarely used in practice. One
example is the fail (‘code’, ‘pattern’)
function
which evaluates ‘code’ in the caller’s context and
checks that the error message it produces matches
the given pattern. Other examples such as save
and load
are written in C++ where all Octave variables
are in the ‘caller’ context and evalin
is not needed.
(context, try)
¶(context, try, catch)
¶Like eval
, except that the expressions are evaluated in the context
context, which may be either "caller"
or "base"
.
(context, varname, value)
¶Assign value to varname in context context, which
may be either "base"
or "caller"
.
See also: evalin.
Statements may be a simple constant expression or a complicated list of nested loops and conditional statements.
Control statements such as if
, while
, and so on
control the flow of execution in Octave programs. All the control
statements start with special keywords such as if
and
while
, to distinguish them from simple expressions.
Many control statements contain other statements; for example, the
if
statement contains another statement which may or may not be
executed.
Each control statement has a corresponding end statement that
marks the end of the control statement. For example, the
keyword endif
marks the end of an if
statement, and
endwhile
marks the end of a while
statement. You can use
the keyword end
anywhere a more specific end keyword is expected,
but using the more specific keywords is preferred because if you use
them, Octave is able to provide better diagnostics for mismatched or
missing end tokens.
The list of statements contained between keywords like if
or
while
and the corresponding end statement is called the
body of a control statement.
The if
statement is Octave’s decision-making statement. There
are three basic forms of an if
statement. In its simplest form,
it looks like this:
if (condition) then-body endif
condition is an expression that controls what the rest of the statement will do. The then-body is executed only if condition is true.
The condition in an if
statement is considered true if its value
is nonzero, and false if its value is zero. If the value of the
conditional expression in an if
statement is a vector or a
matrix, it is considered true only if it is non-empty and all
of the elements are nonzero. The conceptually equivalent code when
condition is a matrix is shown below.
if (matrix) ≡ if (all (matrix(:)))
The second form of an if statement looks like this:
if (condition) then-body else else-body endif
If condition is true, then-body is executed; otherwise, else-body is executed.
Here is an example:
if (rem (x, 2) == 0) printf ("x is even\n"); else printf ("x is odd\n"); endif
In this example, if the expression rem (x, 2) == 0
is true (that
is, the value of x
is divisible by 2), then the first
printf
statement is evaluated, otherwise the second printf
statement is evaluated.
The third and most general form of the if
statement allows
multiple decisions to be combined in a single statement. It looks like
this:
if (condition) then-body elseif (condition) elseif-body else else-body endif
Any number of elseif
clauses may appear. Each condition is
tested in turn, and if one is found to be true, its corresponding
body is executed. If none of the conditions are true and the
else
clause is present, its body is executed. Only one
else
clause may appear, and it must be the last part of the
statement.
In the following example, if the first condition is true (that is, the
value of x
is divisible by 2), then the first printf
statement is executed. If it is false, then the second condition is
tested, and if it is true (that is, the value of x
is divisible
by 3), then the second printf
statement is executed. Otherwise,
the third printf
statement is performed.
if (rem (x, 2) == 0) printf ("x is even\n"); elseif (rem (x, 3) == 0) printf ("x is odd and divisible by 3\n"); else printf ("x is odd\n"); endif
Note that the elseif
keyword must not be spelled else if
,
as is allowed in Fortran. If it is, the space between the else
and if
will tell Octave to treat this as a new if
statement within another if
statement’s else
clause. For
example, if you write
if (c1) body-1 else if (c2) body-2 endif
Octave will expect additional input to complete the first if
statement. If you are using Octave interactively, it will continue to
prompt you for additional input. If Octave is reading this input from a
file, it may complain about missing or mismatched end
statements,
or, if you have not used the more specific end
statements
(endif
, endfor
, etc.), it may simply produce incorrect
results, without producing any warning messages.
It is much easier to see the error if we rewrite the statements above like this,
if (c1) body-1 else if (c2) body-2 endif
using the indentation to show how Octave groups the statements. See Functions and Scripts.
It is very common to take different actions depending on the value of
one variable. This is possible using the if
statement in the
following way
if (X == 1) do_something (); elseif (X == 2) do_something_else (); else do_something_completely_different (); endif
This kind of code can however be very cumbersome to both write and
maintain. To overcome this problem Octave supports the switch
statement. Using this statement, the above example becomes
switch (X) case 1 do_something (); case 2 do_something_else (); otherwise do_something_completely_different (); endswitch
This code makes the repetitive structure of the problem more explicit,
making the code easier to read, and hence maintain. Also, if the
variable X
should change its name, only one line would need
changing compared to one line per case when if
statements are
used.
The general form of the switch
statement is
switch (expression) case label command_list case label command_list … otherwise command_list endswitch
where label can be any expression. However, duplicate
label values are not detected, and only the command_list
corresponding to the first match will be executed. For the
switch
statement to be meaningful at least one
case label command_list
clause must be present,
while the otherwise command_list
clause is optional.
If label is a cell array the corresponding command_list is executed if any of the elements of the cell array match expression. As an example, the following program will print ‘Variable is either 6 or 7’.
A = 7; switch (A) case { 6, 7 } printf ("variable is either 6 or 7\n"); otherwise printf ("variable is neither 6 nor 7\n"); endswitch
As with all other specific end
keywords, endswitch
may be
replaced by end
, but you can get better diagnostics if you use
the specific forms.
One advantage of using the switch
statement compared to using
if
statements is that the labels can be strings. If an
if
statement is used it is not possible to write
if (X == "a string") # This is NOT valid
since a character-to-character comparison between X
and the
string will be made instead of evaluating if the strings are equal.
This special-case is handled by the switch
statement, and it
is possible to write programs that look like this
switch (X) case "a string" do_something … endswitch
The switch
statement is also available in the widely used C
programming language. There are, however, some differences
between the statement in Octave and C
switch
statement of the C language.
switch (foo) case (1) -2 …
would produce surprising results, as would
switch (foo) case (1) case (2) doit (); …
particularly for C programmers. If doit()
should be executed if
foo is either 1
or 2
, the above code should be
written with a cell array like this
switch (foo) case { 1, 2 } doit (); …
In programming, a loop means a part of a program that is (or at least can be) executed two or more times in succession.
The while
statement is the simplest looping statement in Octave.
It repeatedly executes a statement as long as a condition is true. As
with the condition in an if
statement, the condition in a
while
statement is considered true if its value is nonzero, and
false if its value is zero. If the value of the conditional expression
in a while
statement is a vector or a matrix, it is considered
true only if it is non-empty and all of the elements are nonzero.
Octave’s while
statement looks like this:
while (condition) body endwhile
Here body is a statement or list of statements that we call the body of the loop, and condition is an expression that controls how long the loop keeps running.
The first thing the while
statement does is test condition.
If condition is true, it executes the statement body. After
body has been executed, condition is tested again, and if it
is still true, body is executed again. This process repeats until
condition is no longer true. If condition is initially
false, the body of the loop is never executed.
This example creates a variable fib
that contains the first ten
elements of the Fibonacci sequence.
fib = ones (1, 10); i = 3; while (i <= 10) fib (i) = fib (i-1) + fib (i-2); i++; endwhile
Here the body of the loop contains two statements.
The loop works like this: first, the value of i
is set to 3.
Then, the while
tests whether i
is less than or equal to
10. This is the case when i
equals 3, so the value of the
i
-th element of fib
is set to the sum of the previous two
values in the sequence. Then the i++
increments the value of
i
and the loop repeats. The loop terminates when i
reaches 11.
A newline is not required between the condition and the body; but using one makes the program clearer unless the body is very simple.
The do-until
statement is similar to the while
statement,
except that it repeatedly executes a statement until a condition becomes
true, and the test of the condition is at the end of the loop, so the
body of the loop is always executed at least once. As with the
condition in an if
statement, the condition in a do-until
statement is considered true if its value is nonzero, and false if its
value is zero. If the value of the conditional expression in a
do-until
statement is a vector or a matrix, it is considered
true only if it is non-empty and all of the elements are nonzero.
Octave’s do-until
statement looks like this:
do body until (condition)
Here body is a statement or list of statements that we call the body of the loop, and condition is an expression that controls how long the loop keeps running.
This example creates a variable fib
that contains the first ten
elements of the Fibonacci sequence.
fib = ones (1, 10); i = 2; do i++; fib (i) = fib (i-1) + fib (i-2); until (i == 10)
A newline is not required between the do
keyword and the
body; but using one makes the program clearer unless the body is very
simple.
The for
statement makes it more convenient to count iterations of a
loop. The general form of the for
statement looks like this:
for var = expression body endfor
where body stands for any statement or list of statements, expression is any valid expression, and var may take several forms. Usually it is a simple variable name or an indexed variable. If the value of expression is a structure, var may also be a vector with two elements. See Looping Over Structure Elements, below.
The assignment expression in the for
statement works a bit
differently than Octave’s normal assignment statement. Instead of
assigning the complete result of the expression, it assigns each column
of the expression to var in turn. If expression is a range,
a row vector, or a scalar, the value of var will be a scalar each
time the loop body is executed. If var is a column vector or a
matrix, var will be a column vector each time the loop body is
executed.
The following example shows another way to create a vector containing
the first ten elements of the Fibonacci sequence, this time using the
for
statement:
fib = ones (1, 10); for i = 3:10 fib(i) = fib(i-1) + fib(i-2); endfor
This code works by first evaluating the expression 3:10
, to
produce a range of values from 3 to 10 inclusive. Then the variable
i
is assigned the first element of the range and the body of the
loop is executed once. When the end of the loop body is reached, the
next value in the range is assigned to the variable i
, and the
loop body is executed again. This process continues until there are no
more elements to assign.
Within Octave is it also possible to iterate over matrices or cell arrays
using the for
statement. For example consider
disp ("Loop over a matrix") for i = [1,3;2,4] i endfor disp ("Loop over a cell array") for i = {1,"two";"three",4} i endfor
In this case the variable i
takes on the value of the columns of
the matrix or cell matrix. So the first loop iterates twice, producing
two column vectors [1;2]
, followed by [3;4]
, and likewise
for the loop over the cell array. This can be extended to loops over
multi-dimensional arrays. For example:
a = [1,3;2,4]; c = cat (3, a, 2*a); for i = c i endfor
In the above case, the multi-dimensional matrix c is reshaped to a
two-dimensional matrix as reshape (c, rows (c), prod (size (c)(2:end)))
and then the same behavior as a loop over a two-dimensional matrix is produced.
Although it is possible to rewrite all for
loops as while
loops, the Octave language has both statements because often a
for
loop is both less work to type and more natural to think of.
Counting the number of iterations is very common in loops and it can be
easier to think of this counting as part of looping rather than as
something to do inside the loop.
A special form of the for
statement allows you to loop over all
the elements of a structure:
for [ val, key ] = expression body endfor
In this form of the for
statement, the value of expression
must be a structure. If it is, key and val are set to the
name of the element and the corresponding value in turn, until there are
no more elements. For example:
x.a = 1 x.b = [1, 2; 3, 4] x.c = "string" for [val, key] = x key val endfor -| key = a -| val = 1 -| key = b -| val = -| -| 1 2 -| 3 4 -| -| key = c -| val = string
The elements are not accessed in any particular order. If you need to
cycle through the list in a particular way, you will have to use the
function fieldnames
and sort the list yourself.
The break
statement jumps out of the innermost while
,
do-until
, or for
loop that encloses it. The break
statement may only be used within the body of a loop. The following
example finds the smallest divisor of a given integer, and also
identifies prime numbers:
num = 103; div = 2; while (div*div <= num) if (rem (num, div) == 0) break; endif div++; endwhile if (rem (num, div) == 0) printf ("Smallest divisor of %d is %d\n", num, div) else printf ("%d is prime\n", num); endif
When the remainder is zero in the first while
statement, Octave
immediately breaks out of the loop. This means that Octave
proceeds immediately to the statement following the loop and continues
processing. (This is very different from the exit
statement
which stops the entire Octave program.)
Here is another program equivalent to the previous one. It illustrates
how the condition of a while
statement could just as well
be replaced with a break
inside an if
:
num = 103; div = 2; while (1) if (rem (num, div) == 0) printf ("Smallest divisor of %d is %d\n", num, div); break; endif div++; if (div*div > num) printf ("%d is prime\n", num); break; endif endwhile
The continue
statement, like break
, is used only inside
while
, do-until
, or for
loops. It skips over the
rest of the loop body, causing the next cycle around the loop to begin
immediately. Contrast this with break
, which jumps out of the
loop altogether.
Here is an example:
# print elements of a vector of random # integers that are even. # first, create a row vector of 10 random # integers with values between 0 and 100: vec = round (rand (1, 10) * 100); # print what we're interested in: for x = vec if (rem (x, 2) != 0) continue; endif printf ("%d\n", x); endfor
If one of the elements of vec is an odd number, this example skips the print statement for that element, and continues back to the first statement in the loop.
This is not a practical example of the continue
statement, but it
should give you a clear understanding of how it works. Normally, one
would probably write the loop like this:
for x = vec if (rem (x, 2) == 0) printf ("%d\n", x); endif endfor
Octave supports a limited form of exception handling modeled after the unwind-protect form of Lisp.
The general form of an unwind_protect
block looks like this:
unwind_protect body unwind_protect_cleanup cleanup end_unwind_protect
where body and cleanup are both optional and may contain any Octave expressions or commands. The statements in cleanup are guaranteed to be executed regardless of how control exits body.
This is useful to protect temporary changes to global variables from
possible errors. For example, the following code will always restore
the original value of the global variable frobnosticate
even if an error occurs in the first part of the unwind_protect
block.
save_frobnosticate = frobnosticate; unwind_protect frobnosticate = true; … unwind_protect_cleanup frobnosticate = save_frobnosticate; end_unwind_protect
Without unwind_protect
, the value of frobnosticate
would not be restored if an error occurs while evaluating the first part
of the unwind_protect
block because evaluation would stop at the
point of the error and the statement to restore the value would not be
executed.
In addition to unwind_protect, Octave supports another form of
exception handling, the try
block.
The original form of a try
block looks like this:
try body catch cleanup end_try_catch
where body and cleanup are both optional and may contain any Octave expressions or commands. The statements in cleanup are only executed if an error occurs in body.
No warnings or error messages are printed while body is executing.
If an error does occur during the execution of body, cleanup
can use the functions lasterr
or lasterror
to access the
text of the message that would have been printed, as well as its
identifier. The alternative form,
try body catch err cleanup end_try_catch
will automatically store the output of lasterror
in the structure
err. See Errors and Warnings, for more information about the
lasterr
and lasterror
functions.
In the Octave language, most statements end with a newline character and
you must tell Octave to ignore the newline character in order to
continue a statement from one line to the next. Lines that end with the
characters ...
are joined with the following line before they are
divided into tokens by Octave’s parser. For example, the lines
x = long_variable_name ... + longer_variable_name ... - 42
form a single statement.
Any text between the continuation marker and the newline character is ignored. For example, the statement
x = long_variable_name ... # comment one + longer_variable_name ...comment two - 42 # last comment
is equivalent to the one shown above.
Inside double-quoted string constants, the character \
has to be
used as continuation marker. The \
must appear at the end of the
line just before the newline character:
s = "This text starts in the first line \ and is continued in the second line."
Input that occurs inside parentheses can be continued to the next line without having to use a continuation marker. For example, it is possible to write statements like
if (fine_dining_destination == on_a_boat || fine_dining_destination == on_a_train) seuss (i, will, not, eat, them, sam, i, am, i, will, not, eat, green, eggs, and, ham); endif
without having to add to the clutter with continuation markers.
Complicated Octave programs can often be simplified by defining functions. Functions can be defined directly on the command line during interactive Octave sessions, or in external files, and can be called just like built-in functions.
There are seven different things covered in this section.
Both function files and script files end with an extension of .m, for MATLAB compatibility. If you want more than one independent functions in a file, it must be a script file (see Script Files), and to use these functions you must execute the script file before you can use the functions that are in the script file.
In its simplest form, the definition of a function named name looks like this:
function name body endfunction
A valid function name is like a valid variable name: a sequence of letters, digits and underscores, not starting with a digit. Functions share the same pool of names as variables.
The function body consists of Octave statements. It is the most important part of the definition, because it says what the function should actually do.
For example, here is a function that, when executed, will ring the bell on your terminal (assuming that it is possible to do so):
function wakeup printf ("\a"); endfunction
The printf
statement (see Input and Output) simply tells
Octave to print the string "\a"
. The special character
‘\a’ stands for the alert character (ASCII 7). See Strings.
Once this function is defined, you can ask Octave to evaluate it by typing the name of the function.
Normally, you will want to pass some information to the functions you define. The syntax for passing parameters to a function in Octave is
function name (arg-list) body endfunction
where arg-list is a comma-separated list of the function’s arguments. When the function is called, the argument names are used to hold the argument values given in the call. The list of arguments may be empty, in which case this form is equivalent to the one shown above.
To print a message along with ringing the bell, you might modify the
wakeup
to look like this:
function wakeup (message) printf ("\a%s\n", message); endfunction
Calling this function using a statement like this
wakeup ("Rise and shine!");
will cause Octave to ring your terminal’s bell and print the message
‘Rise and shine!’, followed by a newline character (the ‘\n’
in the first argument to the printf
statement).
In most cases, you will also want to get some information back from the functions you define. Here is the syntax for writing a function that returns a single value:
function ret-var = name (arg-list) body endfunction
The symbol ret-var is the name of the variable that will hold the value to be returned by the function. This variable must be defined before the end of the function body in order for the function to return a value.
Variables used in the body of a function are local to the function. Variables named in arg-list and ret-var are also local to the function. See Global Variables, for information about how to access global variables inside a function.
For example, here is a function that computes the average of the elements of a vector:
function retval = avg (v) retval = sum (v) / length (v); endfunction
If we had written avg
like this instead,
function retval = avg (v) if (isvector (v)) retval = sum (v) / length (v); endif endfunction
and then called the function with a matrix instead of a vector as the argument, Octave would have printed an error message like this:
error: value on right hand side of assignment is undefined
because the body of the if
statement was never executed, and
retval
was never defined. To prevent obscure errors like this,
it is a good idea to always make sure that the return variables will
always have values, and to produce meaningful error messages when
problems are encountered. For example, avg
could have been
written like this:
function retval = avg (v) retval = 0; if (isvector (v)) retval = sum (v) / length (v); else error ("avg: expecting vector argument"); endif endfunction
There is still one remaining problem with this function. What if it is
called without an argument? Without additional error checking, Octave
will probably print an error message that won’t really help you track
down the source of the error. To allow you to catch errors like this,
Octave provides each function with an automatic variable called
nargin
. Each time a function is called, nargin
is
automatically initialized to the number of arguments that have actually
been passed to the function. For example, we might rewrite the
avg
function like this:
function retval = avg (v) retval = 0; if (nargin != 1) usage ("avg (vector)"); endif if (isvector (v)) retval = sum (v) / length (v); else error ("avg: expecting vector argument"); endif endfunction
Octave automatically reports an error for functions written in .m file code if they are called with more arguments than expected. Octave does not automatically report an error if a function is called with too few arguments, since functions in general may have default arguments, but any attempt to use a variable that has not been given a value will result in an error. Functions can check the arguments they are called with to avoid such problems and to provide more context-specific error messages.
n =
nargin ()
¶n =
nargin (fcn)
¶Report the number of input arguments to a function.
Called from within a function, return the number of arguments passed to the function. At the top level, return the number of command line arguments passed to Octave.
If called with the optional argument fcn—a function name or handle—return the declared number of arguments that the function can accept.
If the last argument to fcn is varargin the returned value is
negative. For example, the function union
for sets is declared as
function [y, ia, ib] = union (a, b, varargin) and nargin ("union") ⇒ -3
Programming Note: nargin
does not work on compiled functions
(.oct files) such as built-in or dynamically loaded functions.
namestr =
inputname (n)
¶namestr =
inputname (n, ids_only)
¶Return the name of the n-th argument to the calling function.
If the argument is not a simple variable name, return an empty string.
Examples which will return ""
are numbers (5.1
),
expressions (y/2
), and cell or structure indexing
(c{1}
or s.field
).
inputname
is only useful within a function. When used at the command
line or within a script it always returns an empty string.
By default, return an empty string if the n-th argument is not a valid variable name. If the optional argument ids_only is false, return the text of the argument even if it is not a valid variable name. This is an Octave extension that allows the programmer to view exactly how the function was invoked even when the inputs are complex expressions.
val =
silent_functions ()
¶old_val =
silent_functions (new_val)
¶old_val =
silent_functions (new_val, "local")
¶Query or set the internal variable that controls whether internal output from a function is suppressed.
If this option is disabled, Octave will display the results produced by evaluating expressions within a function body that are not terminated with a semicolon.
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 body of a user-defined function can contain a return
statement.
This statement returns control to the rest of the Octave program. It
looks like this:
return
Unlike the return
statement in C, Octave’s return
statement cannot be used to return a value from a function. Instead,
you must assign values to the list of return variables that are part of
the function
statement. The return
statement simply makes
it easier to exit a function from a deeply nested loop or conditional
statement.
Here is an example of a function that checks to see if any elements of a vector are nonzero.
function retval = any_nonzero (v) retval = 0; for i = 1:length (v) if (v (i) != 0) retval = 1; return; endif endfor printf ("no nonzero elements found\n"); endfunction
Note that this function could not have been written using the
break
statement to exit the loop once a nonzero value is found
without adding extra logic to avoid printing the message if the vector
does contain a nonzero element.
When Octave encounters the keyword return
inside a function or
script, it returns control to the caller immediately. At the top level,
the return statement is ignored. A return
statement is assumed
at the end of every function definition.
Unlike many other computer languages, Octave allows you to define functions that return more than one value. The syntax for defining functions that return multiple values is
function [ret-list] = name (arg-list) body endfunction
where name, arg-list, and body have the same meaning
as before, and ret-list is a comma-separated list of variable
names that will hold the values returned from the function. The list of
return values must have at least one element. If ret-list has
only one element, this form of the function
statement is
equivalent to the form described in the previous section.
Here is an example of a function that returns two values, the maximum element of a vector and the index of its first occurrence in the vector.
function [max, idx] = vmax (v) idx = 1; max = v (idx); for i = 2:length (v) if (v (i) > max) max = v (i); idx = i; endif endfor endfunction
In this particular case, the two values could have been returned as elements of a single array, but that is not always possible or convenient. The values to be returned may not have compatible dimensions, and it is often desirable to give the individual return values distinct names.
It is possible to use the nthargout
function to obtain only some
of the return values or several at once in a cell array.
See Cell Array Objects.
arg =
nthargout (n, fcn, …)
¶arg =
nthargout (n, ntot, fcn, …)
¶Return the nth output argument of the function specified by the function handle or string fcn.
Any additional arguments are passed directly to fcn. The total number of arguments to call fcn with can be passed in ntot; by default ntot is n. The input n can also be a vector of indices of the output, in which case the output will be a cell array of the requested output arguments.
The intended use of nthargout
is to avoid intermediate variables.
For example, when finding the indices of the maximum entry of a matrix, the
following two compositions of nthargout
m = magic (5); cell2mat (nthargout ([1, 2], @ind2sub, size (m), nthargout (2, @max, m(:)))) ⇒ 5 3
are completely equivalent to the following lines:
m = magic (5); [~, idx] = max (M(:)); [i, j] = ind2sub (size (m), idx); [i, j] ⇒ 5 3
It can also be helpful to have all output arguments collected in a single cell array as the following code demonstrates:
USV = nthargout ([1:3], @svd, hilb (5));
In addition to setting nargin
each time a function is called,
Octave also automatically initializes nargout
to the number of
values that are expected to be returned. This allows you to write
functions that behave differently depending on the number of values that
the user of the function has requested. The implicit assignment to the
built-in variable ans
does not figure in the count of output
arguments, so the value of nargout
may be zero.
The svd
and hist
functions are examples of built-in
functions that behave differently depending on the value of
nargout
. For example, hist
will draw a histogram when called
with no output variables, but if called with outputs it will return the
frequency counts and/or bin centers without creating a plot.
It is possible to write functions that only set some return values. For example, calling the function
function [x, y, z] = f () x = 1; z = 2; endfunction
as
[a, b, c] = f ()
produces:
a = 1 b = [](0x0) c = 2
along with a warning.
n =
nargout ()
¶n =
nargout (fcn)
¶Report the number of output arguments from a function.
Called from within a function, return the number of values the caller
expects to receive. At the top level, nargout
with no argument is
undefined and will produce an error.
If called with the optional argument fcn—a function name or handle—return the number of declared output values that the function can produce.
If the final output argument is varargout the returned value is negative.
For example,
f ()
will cause nargout
to return 0 inside the function f
and
[s, t] = f ()
will cause nargout
to return 2 inside the function f
.
In the second usage,
nargout (@histc) # or nargout ("histc") using a string input
will return 2, because histc
has two outputs, whereas
nargout (@imread)
will return -2, because imread
has two outputs and the second is
varargout.
Programming Note. nargout
does not work for built-in functions and
returns -1 for all anonymous functions.
It is possible to return a variable number of output arguments from a
function using a syntax that’s similar to the one used with the
special varargin
parameter name. To let a function return a
variable number of output arguments the special output parameter name
varargout
is used. As with varargin
, varargout
is
a cell array that will contain the requested output arguments.
As an example the following function sets the first output argument to 1, the second to 2, and so on.
function varargout = one_to_n () for i = 1:nargout varargout{i} = i; endfor endfunction
When called this function returns values like this
[a, b, c] = one_to_n () ⇒ a = 1 ⇒ b = 2 ⇒ c = 3
If varargin
(varargout
) does not appear as the last
element of the input (output) parameter list, then it is not special,
and is handled the same as any other parameter name.
[r1, r2, …, rn] =
deal (a)
¶[r1, r2, …, rn] =
deal (a1, a2, …, an)
¶Copy the input parameters into the corresponding output parameters.
If only a single input parameter is supplied, its value is copied to each of the outputs.
For example,
[a, b, c] = deal (x, y, z);
is equivalent to
a = x; b = y; c = z;
and
[a, b, c] = deal (x);
is equivalent to
a = b = c = x;
Programming Note: deal
is often used with comma-separated lists
derived from cell arrays or structures. This is unnecessary as the
interpreter can perform the same action without the overhead of a function
call. For example:
c = {[1 2], "Three", 4}; [x, y, z] = c{:} ⇒ x = 1 2 y = Three z = 4
See also: cell2struct, struct2cell, repmat.
Sometimes the number of input arguments is not known when the function is defined. As an example think of a function that returns the smallest of all its input arguments. For example:
a = smallest (1, 2, 3); b = smallest (1, 2, 3, 4);
In this example both a
and b
would be 1. One way to write
the smallest
function is
function val = smallest (arg1, arg2, arg3, arg4, arg5) body endfunction
and then use the value of nargin
to determine which of the input
arguments should be considered. The problem with this approach is
that it can only handle a limited number of input arguments.
If the special parameter name varargin
appears at the end of a
function parameter list it indicates that the function takes a variable
number of input arguments. Using varargin
the function
looks like this
function val = smallest (varargin) body endfunction
In the function body the input arguments can be accessed through the
variable varargin
. This variable is a cell array containing
all the input arguments. See Cell Arrays, for details on working
with cell arrays. The smallest
function can now be defined
like this
function val = smallest (varargin) val = min ([varargin{:}]); endfunction
This implementation handles any number of input arguments, but it’s also a very simple solution to the problem.
A slightly more complex example of varargin
is a function
print_arguments
that prints all input arguments. Such a function
can be defined like this
function print_arguments (varargin) for i = 1:length (varargin) printf ("Input argument %d: ", i); disp (varargin{i}); endfor endfunction
This function produces output like this
print_arguments (1, "two", 3); -| Input argument 1: 1 -| Input argument 2: two -| Input argument 3: 3
[reg, prop] =
parseparams (params)
¶[reg, var1, …] =
parseparams (params, name1, default1, …)
¶Return in reg the cell elements of param up to the first string element and in prop all remaining elements beginning with the first string element.
For example:
[reg, prop] = parseparams ({1, 2, "linewidth", 10}) reg = { [1,1] = 1 [1,2] = 2 } prop = { [1,1] = linewidth [1,2] = 10 }
The parseparams function may be used to separate regular numeric arguments from additional arguments given as property/value pairs of the varargin cell array.
In the second form of the call, available options are specified directly with their default values given as name-value pairs. If params do not form name-value pairs, or if an option occurs that does not match any of the available options, an error occurs.
When called from an m-file function, the error is prefixed with the name of the caller function.
The matching of options is case-insensitive.
See also: varargin, inputParser.
In the formal argument list, it is possible to use the dummy placeholder
~
instead of a name. This indicates that the corresponding argument
value should be ignored and not stored to any variable.
function val = pick2nd (~, arg2) val = arg2; endfunction
The value of nargin
is not affected by using this declaration.
Return arguments can also be ignored using the same syntax. For example, the
sort function returns both the sorted values, and an index vector for the
original input which will result in a sorted output. Ignoring the second
output is simple—don’t request more than one output. But ignoring the first,
and calculating just the second output, requires the use of the ~
placeholder.
x = [2, 3, 1]; [s, i] = sort (x) ⇒ s = 1 2 3 i = 3 1 2 [~, i] = sort (x) ⇒ i = 3 1 2
When using the ~
placeholder, commas—not whitespace—must be used
to separate output arguments. Otherwise, the interpreter will view ~
as
the logical not operator.
[~ i] = sort (x) parse error: invalid left hand side of assignment
Functions may take advantage of ignored outputs to reduce the number of
calculations performed. To do so, use the isargout
function to query
whether the output argument is wanted. For example:
function [out1, out2] = long_function (x, y, z) if (isargout (1)) ## Long calculation … out1 = result; endif … endfunction
tf =
isargout (k)
¶Within a function, return a logical value indicating whether the argument k will be assigned to a variable on output.
If the result is false, the argument has been ignored during the function
call through the use of the tilde (~) special output argument. Functions
can use isargout
to avoid performing unnecessary calculations for
outputs which are unwanted.
If k is outside the range 1:max (nargout)
, the function returns
false. k can also be an array, in which case the function works
element-by-element and a logical array is returned. At the top level,
isargout
returns an error.
Since Octave supports variable number of input arguments, it is very useful to assign default values to some input arguments. When an input argument is declared in the argument list it is possible to assign a default value to the argument like this
function name (arg1 = val1, …) body endfunction
If no value is assigned to arg1 by the user, it will have the value val1.
As an example, the following function implements a variant of the classic “Hello, World” program.
function hello (who = "World") printf ("Hello, %s!\n", who); endfunction
When called without an input argument the function prints the following
hello (); -| Hello, World!
and when it’s called with an input argument it prints the following
hello ("Beautiful World of Free Software"); -| Hello, Beautiful World of Free Software!
Sometimes it is useful to explicitly tell Octave to use the default value of an input argument. This can be done writing a ‘:’ as the value of the input argument when calling the function.
hello (:); -| Hello, World!
Octave is a weakly typed programming language. Thus it is possible to call a function with arguments, that probably cause errors or might have undesirable side effects. For example calling a string processing function with a huge sparse matrix.
It is good practice at the head of a function to verify that it has been called correctly. Octave offers several functions for this purpose.
In Octave the following idiom is seen frequently at the beginning of a function definition:
if (nargin < min_#_inputs || nargin > max_#_inputs) print_usage (); endif
which stops the function execution and prints a message about the correct way to call the function whenever the number of inputs is wrong.
Similar error checking is provided by narginchk
and
nargoutchk
.
(minargs, maxargs)
¶Check for correct number of input arguments.
Generate an error message if the number of arguments in the calling function is outside the range minargs and maxargs. Otherwise, do nothing.
Both minargs and maxargs must be scalar numeric values. Zero, Inf, and negative values are all allowed, and minargs and maxargs may be equal.
Note that this function evaluates nargin
on the caller.
See also: nargoutchk, error, nargout, nargin.
(minargs, maxargs)
¶msgstr =
nargoutchk (minargs, maxargs, nargs)
¶msgstr =
nargoutchk (minargs, maxargs, nargs, "string")
¶msgstruct =
nargoutchk (minargs, maxargs, nargs, "struct")
¶Check for correct number of output arguments.
In the first form, return an error if the number of arguments is not between
minargs and maxargs. Otherwise, do nothing. Note that this
function evaluates the value of nargout
on the caller so its value
must have not been tampered with.
Both minargs and maxargs must be numeric scalars. Zero, Inf, and negative are all valid, and they can have the same value.
For backwards compatibility, the other forms return an appropriate error message string (or structure) if the number of outputs requested is invalid.
This is useful for checking to that the number of output arguments supplied to a function is within an acceptable range.
Besides the number of arguments, inputs can be checked for various
properties. validatestring
is used for string arguments and
validateattributes
for numeric arguments.
validstr =
validatestring (str, strarray)
¶validstr =
validatestring (str, strarray, funcname)
¶validstr =
validatestring (str, strarray, funcname, varname)
¶validstr =
validatestring (…, position)
¶Verify that str is an element, or substring of an element, in strarray.
When str is a character string to be tested, and strarray is a
cell array of strings of valid values, then validstr will be the
validated form of str where validation is defined as str being
a member or substring of validstr. This is useful for both verifying
and expanding short options, such as "r"
, to their longer forms,
such as "red"
. If str is a substring of validstr,
and there are multiple matches, the shortest match will be returned if
all matches are substrings of each other. Otherwise, an error will be
raised because the expansion of str is ambiguous. All comparisons
are case insensitive.
The additional inputs funcname, varname, and position are optional and will make any generated validation error message more specific.
Examples:
validatestring ("r", {"red", "green", "blue"}) ⇒ "red" validatestring ("b", {"red", "green", "blue", "black"}) ⇒ error: validatestring: multiple unique matches were found for 'b': blue, black
See also: strcmp, strcmpi, validateattributes, inputParser.
(A, classes, attributes)
¶(A, classes, attributes, arg_idx)
¶(A, classes, attributes, func_name)
¶(A, classes, attributes, func_name, arg_name)
¶(A, classes, attributes, func_name, arg_name, arg_idx)
¶Check validity of input argument.
Confirms that the argument A is valid by belonging to one of classes, and holding all of the attributes. If it does not, an error is thrown, with a message formatted accordingly. The error message can be made further complete by the function name fun_name, the argument name arg_name, and its position in the input arg_idx.
classes must be a cell array of strings (an empty cell array is allowed) with the name of classes (remember that a class name is case sensitive). In addition to the class name, the following categories names are also valid:
"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.
attributes must be a cell array with names of checks for A. Some of them require an additional value to be supplied right after the name (see details for each below).
"<="
All values are less than or equal to the following value in attributes.
"<"
All values are less than the following value in attributes.
">="
All values are greater than or equal to the following value in attributes.
">"
All values are greater than the following value in attributes.
"2d"
A 2-dimensional matrix. Note that vectors and empty matrices have 2 dimensions, one of them being of length 1, or both length 0.
"3d"
Has no more than 3 dimensions. A 2-dimensional matrix is a 3-D matrix whose 3rd dimension is of length 1.
"binary"
All values are either 1 or 0.
"column"
Values are arranged in a single column.
"decreasing"
No value is NaN, and each is less than the preceding one.
"diag"
Value is a diagonal matrix.
"even"
All values are even numbers.
"finite"
All values are finite.
"increasing"
No value is NaN, and each is greater than the preceding one.
"integer"
All values are integer. This is different than using isinteger
which only checks its an integer type. This checks that each value in
A is an integer value, i.e., it has no decimal part.
"ncols"
Has exactly as many columns as the next value in attributes.
"ndims"
Has exactly as many dimensions as the next value in attributes.
"nondecreasing"
No value is NaN, and each is greater than or equal to the preceding one.
"nonempty"
It is not empty.
"nonincreasing"
No value is NaN, and each is less than or equal to the preceding one.
"nonnan"
No value is a NaN
.
"nonnegative"
All values are non negative.
"nonsparse"
It is not a sparse matrix.
"nonzero"
No value is zero.
"nrows"
Has exactly as many rows as the next value in attributes.
"numel"
Has exactly as many elements as the next value in attributes.
"odd"
All values are odd numbers.
"positive"
All values are positive.
"real"
It is a non-complex matrix.
"row"
Values are arranged in a single row.
"scalar"
It is a scalar.
"size"
Its size has length equal to the values of the next in attributes.
The next value must is an array with the length for each dimension. To
ignore the check for a certain dimension, the value of NaN
can be
used.
"square"
Is a square matrix.
"vector"
Values are arranged in a single vector (column or vector).
See also: isa, validatestring, inputParser.
As alternatives to validateattributes
there are several shorter
convenience functions to check for individual properties.
(x)
¶Require that input x is finite.
Raise an error if any element of the input x is not finite, as
determined by isfinite (x)
.
See also: mustBeNonNan, isfinite.
(x, c)
¶Require that input x is greater than c.
Raise an error if any element of the input x is not greater than
c, as determined by x > c
.
See also: mustBeGreaterThanOrEqual, mustBeLessThan, gt.
(x, c)
¶Require that input x is greater than or equal to c.
Raise an error if any element of the input x is not greater than
or equal to c, as determined by x >= c
.
See also: mustBeGreaterThan, mustBeLessThanOrEqual, ge.
(x)
¶Require that input x is integer-valued (but not necessarily integer-typed).
Raise an error if any element of the input x is not a finite, real, integer-valued numeric value, as determined by various checks.
See also: mustBeNumeric.
(x, c)
¶Require that input x is less than c.
Raise an error if any element of the input x is not less than
c, as determined by x < c
.
See also: mustBeLessThanOrEqual, mustBeGreaterThan, lt.
(x, c)
¶Require that input is less than or equal to a given value.
Raise an error if any element of the input x is not less than
or equal to c, as determined by x <= c
.
See also: mustBeLessThan, mustBeGreaterThanOrEqual, le.
(x, valid)
¶Require that input x is a member of a set of given valid values.
Raise an error if any element of the input x is not a member
of the set valid, as determined by ismember (x)
.
Programming Note: char inputs may behave strangely because of the
interaction between chars and cellstrings when calling ismember
on
them. But it will probably "do what you mean" if you just use it naturally.
To guarantee operation, convert all char arrays to cellstrings with
cellstr
.
See also: mustBeNonempty, ismember.
(x)
¶Require that input x is negative.
Raise an error if any element of the input x is not negative, as
determined by x < 0
.
See also: mustBeNonnegative.
(x)
¶Require that input x is nonempty.
Raise an error if the input x is empty, as determined by
isempty (x)
.
See also: mustBeMember, mustBeNonzero, isempty.
(x)
¶Require that input x is non-NaN
.
Raise an error if any element of the input x is NaN
, as
determined by isnan (x)
.
See also: mustBeFinite, mustBeNonempty, isnan.
(x)
¶Require that input x is not negative.
Raise an error if any element of the input x is negative, as
determined by x >= 0
.
See also: mustBeNonzero, mustBePositive.
(x)
¶Require that input x is not positive.
Raise an error if any element of the input x is positive, as
determined by x <= 0
.
See also: mustBeNegative, mustBeNonzero.
(x)
¶Require that input x is not sparse.
Raise an error if the input x is sparse, as determined by
issparse (x)
.
See also: issparse.
(x)
¶Require that input x is not zero.
Raise an error if any element of the input x is zero, as determined
by x == 0
.
See also: mustBeNonnegative, mustBePositive.
(x)
¶Require that input x is numeric.
Raise an error if the input x is not numeric, as determined by
isnumeric (x)
.
See also: mustBeNumericOrLogical, isnumeric.
(x)
¶Require that input x is numeric or logical.
Raise an error if the input x is not numeric or logical, as
determined by isnumeric (x) || islogical (x)
.
See also: mustBeNumeric, isnumeric, islogical.
(x)
¶Require that input x is positive.
Raise an error if any element of the input x is not positive, as
determined by x > 0
.
See also: mustBeNonnegative, mustBeNonzero.
(x)
¶Require that input x is real.
Raise an error if the input x is not real, as determined by
isreal (x)
.
See also: mustBeFinite, mustBeNonNan, isreal.
If none of the preceding validation functions is sufficient there is also
the class inputParser
which can perform extremely complex input
checking for functions.
p =
inputParser ()
¶Create object p of the inputParser class.
This class is designed to allow easy parsing of function arguments. The class supports four types of arguments:
addRequired
);
addOptional
);
addParameter
);
addSwitch
).
After defining the function API with these methods, the supplied arguments
can be parsed with the parse
method and the parsing results
accessed with the Results
accessor.
Return list of parameter names already defined.
Return structure with argument names as fieldnames and corresponding values.
Return structure similar to Results
, but for unmatched parameters.
See the KeepUnmatched
property.
Return cell array with the names of arguments that are using default values.
= boolean
¶Set whether matching of argument names should be case sensitive. Defaults to false.
= name
¶Set function name to be used in error messages; Defaults to empty string.
= boolean
¶Set whether an error should be given for non-defined arguments. Defaults
to false. If set to true, the extra arguments can be accessed through
Unmatched
after the parse
method. Note that since
Switch
and Parameter
arguments can be mixed, it is
not possible to know the unmatched type. If argument is found unmatched
it is assumed to be of the Parameter
type and it is expected to
be followed by a value.
= boolean
¶Set whether a structure can be passed to the function instead of parameter/value pairs. Defaults to true.
The following example shows how to use this class:
function check (varargin) p = inputParser (); # create object p.FunctionName = "check"; # set function name p.addRequired ("pack", @ischar); # mandatory argument p.addOptional ("path", pwd(), @ischar); # optional argument ## create a function handle to anonymous functions for validators val_mat = @(x) isvector (x) && all (x <= 1) && all (x >= 0); p.addOptional ("mat", [0 0], val_mat); ## create two arguments of type "Parameter" val_type = @(x) any (strcmp (x, {"linear", "quadratic"})); p.addParameter ("type", "linear", val_type); val_verb = @(x) any (strcmp (x, {"low", "medium", "high"})); p.addParameter ("tolerance", "low", val_verb); ## create a switch type of argument p.addSwitch ("verbose"); p.parse (varargin{:}); # Run created parser on inputs ## the rest of the function can access inputs by using p.Results. ## for example, get the tolerance input with p.Results.tolerance endfunction
check ("mech"); # valid, use defaults for other arguments check (); # error, one argument is mandatory check (1); # error, since ! ischar check ("mech", "~/dev"); # valid, use defaults for other arguments check ("mech", "~/dev", [0 1 0 0], "type", "linear"); # valid ## following is also valid. Note how the Switch argument type can ## be mixed into or before the Parameter argument type (but it ## must still appear after any Optional argument). check ("mech", "~/dev", [0 1 0 0], "verbose", "tolerance", "high"); ## following returns an error since not all optional arguments, ## 'path' and 'mat', were given before the named argument 'type'. check ("mech", "~/dev", "type", "linear");
Note 1: A function can have any mixture of the four API types but
they must appear in a specific order. Required
arguments must be
first and can be followed by any Optional
arguments. Only
the Parameter
and Switch
arguments may be mixed
together and they must appear at the end.
Note 2: If both Optional
and Parameter
arguments
are mixed in a function API then once a string Optional argument fails to
validate it will be considered the end of the Optional
arguments. The remaining arguments will be compared against any
Parameter
or Switch
arguments.
See also: nargin, validateattributes, validatestring, varargin.
Except for simple one-shot programs, it is not practical to have to define all the functions you need each time you need them. Instead, you will normally want to save them in a file so that you can easily edit them, and save them for use at a later time.
Octave does not require you to load function definitions from files before using them. You simply need to put the function definitions in a place where Octave can find them.
When Octave encounters an identifier that is undefined, it first looks for variables or functions that are already compiled and currently listed in its symbol table. If it fails to find a definition there, it searches a list of directories (the path) for files ending in .m that have the same base name as the undefined identifier.5 Once Octave finds a file with a name that matches, the contents of the file are read. If it defines a single function, it is compiled and executed. See Script Files, for more information about how you can define more than one function in a single file.
When Octave defines a function from a function file, it saves the full name of the file it read and the time stamp on the file. If the time stamp on the file changes, Octave may reload the file. When Octave is running interactively, time stamp checking normally happens at most once each time Octave prints the prompt. Searching for new function definitions also occurs if the current working directory changes.
Checking the time stamp allows you to edit the definition of a function while Octave is running, and automatically use the new function definition without having to restart your Octave session.
To avoid degrading performance unnecessarily by checking the time stamps on functions that are not likely to change, Octave assumes that function files in the directory tree octave-home/share/octave/version/m will not change, so it doesn’t have to check their time stamps every time the functions defined in those files are used. This is normally a very good assumption and provides a significant improvement in performance for the function files that are distributed with Octave.
If you know that your own function files will not change while you are
running Octave, you can improve performance by calling
ignore_function_time_stamp ("all")
, so that Octave will
ignore the time stamps for all function files. Passing
"system"
to this function resets the default behavior.
name
¶field value
¶value =
edit ("get", field)
¶value =
edit ("get", "all")
¶Edit the named function, or change editor settings.
If edit
is called with the name of a file or function as its
argument it will be opened in the text editor defined by EDITOR
.
".m"
, will be considered. If still no file is
found, then variants with a leading "@"
and then with both a
leading "@"
and trailing ".m"
will be considered.
name.cc
is specified, then it will search for
name.cc in the path and open it in the editor. If the file is
not found, then a new .cc file will be created. If name
happens to be an m-file or command-line function, then the text of that
function will be inserted into the .cc file as a comment.
Warning: You may need to clear name before the new definition
is available. If you are editing a .cc file, you will need to execute
mkoctfile name.cc
before the definition will be
available.
If edit
is called with field and value variables, the
value of the control field field will be set to value.
If an output argument is requested and the first input argument is
get
then edit
will return the value of the control field
field. If the control field does not exist, edit will return a
structure containing all fields and values. Thus, edit ("get",
returns a complete control structure.
"all"
)
The following control fields are used:
This is the name to put after the "## Author:" field of new functions. By
default it guesses from the gecos
field of the password database.
This is the e-mail address to list after the name in the author field. By
default it guesses <$LOGNAME@$HOSTNAME>
, and if $HOSTNAME
is not defined it uses uname -n
. You probably want to override
this. Be sure to use the format user@host
.
GNU General Public License (default).
BSD-style license without advertising clause.
Public domain.
Your own default copyright and license.
Unless you specify ‘pd’, edit will prepend the copyright statement with "Copyright (C) YYYY Author".
This value determines whether the editor should be started in async mode
(editor is started in the background and Octave continues) or sync mode
(Octave waits until the editor exits). Set it to "sync"
to start
the editor in sync mode. The default is "async"
(see system
).
Determines whether files should be edited in place, without regard to
whether they are modifiable or not. The default is true
.
Set it to false
to have read-only function files automatically
copied to ‘home’, if it exists, when editing them.
This value indicates a directory that system m-files should be copied into
before opening them in the editor. The intent is that this directory is
also in the path, so that the edited copy of a system function file shadows
the original. This setting only has an effect when ‘editinplace’ is
set to false
. The default is the empty matrix ([]
), which
means it is not used. The default in previous versions of Octave was
~/octave.
()
¶("fullpath")
¶("fullpathext")
¶Return the name of the currently executing file.
The base name of the currently executing script or function is returned without any extension. If called from outside an m-file, such as the command line, return the empty string.
Given the argument "fullpath"
, include the directory part of the
filename, but not the extension.
Given the argument "fullpathext"
, include the directory part of
the filename and the extension.
val =
ignore_function_time_stamp ()
¶old_val =
ignore_function_time_stamp (new_val)
¶Query or set the internal variable that controls whether Octave checks the time stamp on files each time it looks up functions defined in function files.
If the internal variable is set to "system"
, Octave will not
automatically recompile function files in subdirectories of
octave-home/share/version/m if they have changed since
they were last compiled, but will recompile other function files in the
search path if they change.
If set to "all"
, Octave will not recompile any function files
unless their definitions are removed with clear
.
If set to "none"
, Octave will always check time stamps on files
to determine whether functions defined in function files need to
recompiled.
When a function is called, Octave searches a list of directories for
a file that contains the function declaration. This list of directories
is known as the load path. By default the load path contains
a list of directories distributed with Octave plus the current
working directory. To see your current load path call the path
function without any input or output arguments.
It is possible to add or remove directories to or from the load path
using addpath
and rmpath
. As an example, the following
code adds ‘~/Octave’ to the load path.
addpath ("~/Octave")
After this the directory ‘~/Octave’ will be searched for functions.
(dir1, …)
¶(dir1, …, option)
¶oldpath =
addpath (…)
¶Add named directories to the function search path.
If option is "-begin"
or 0 (the default), prepend the directory
name(s) to the current path. If option is "-end"
or 1, append
the directory name(s) to the current path. Directories added to the path must
exist.
In addition to accepting individual directory arguments, lists of
directory names separated by pathsep
are also accepted. For example:
addpath ("dir1:/dir2:~/dir3")
The newly added paths appear in the load path in the same order that they
appear in the arguments of addpath
. When extending the load path to
the front, the last path in the list of arguments is added first. When
extending the load path to the end, the first path in the list of arguments
is added first.
For each directory that is added, and that was not already in the path,
addpath
checks for the existence of a file named PKG_ADD
(note lack of .m extension) and runs it if it exists.
See also: path, rmpath, genpath, pathdef, savepath, pathsep.
pathstr =
genpath (dir)
¶pathstr =
genpath (dir, skipdir1, …)
¶Return a path constructed from dir and all its subdirectories.
The path does not include package directories (beginning with ‘+’), old-style class directories (beginning with ‘@’), private directories, or any subdirectories of these types.
If additional string parameters are given, the resulting path will exclude directories with those names.
(dir1, …)
¶oldpath =
rmpath (dir1, …)
¶Remove dir1, … from the current function search path.
In addition to accepting individual directory arguments, lists of
directory names separated by pathsep
are also accepted. For example:
rmpath ("dir1:/dir2:~/dir3")
For each directory that is removed, rmpath
checks for the
existence of a file named PKG_DEL (note lack of .m extension)
and runs it if it exists.
See also: path, addpath, genpath, pathdef, savepath, pathsep.
file
¶status =
savepath (…)
¶Save the unique portion of the current function search path that is not set during Octave’s initialization process to file.
If file is omitted, Octave looks in the current directory for a project-specific .octaverc file in which to save the path information. If no such file is present then the user’s configuration file ~/.octaverc is used.
If successful, savepath
returns 0.
The savepath
function makes it simple to customize a user’s
configuration file to restore the working paths necessary for a particular
instance of Octave. Assuming no filename is specified, Octave will
automatically restore the saved directory paths from the appropriate
.octaverc file when starting up. If a filename has been specified
then the paths may be restored manually by calling source file
.
()
¶str =
path ()
¶str =
path (path1, …)
¶Modify or display Octave’s load path.
If nargin and nargout are zero, display the elements of Octave’s load path in an easy to read format.
If nargin is zero and nargout is greater than zero, return the current load path.
If nargin is greater than zero, concatenate the arguments,
separating them with pathsep
. Set the internal search path
to the result and return it.
No checks are made for duplicate elements.
See also: addpath, rmpath, genpath, pathdef, savepath, pathsep.
val =
pathdef ()
¶Return the default path for Octave.
The path information is extracted from one of four sources. The possible sources, in order of preference, are:
()
¶Reinitialize Octave’s load path directory cache.
fname =
file_in_loadpath (file)
¶fname =
file_in_loadpath (file, "all")
¶Return the absolute name of file if it can be found in the list of
directories specified by path
.
If no file is found, return an empty character string.
When file is already an absolute name, the name is checked against the file system instead of Octave’s loadpath. In this case, if file exists it will be returned in fname, otherwise an empty string is returned.
If the first argument is a cell array of strings, search each directory of the loadpath for element of the cell array and return the first that matches.
If the second optional argument "all"
is supplied, return a cell
array containing the list of all files that have the same name in the path.
If no files are found, return an empty cell array.
See also: file_in_path, dir_in_loadpath, path.
pathstr =
restoredefaultpath ()
¶Restore Octave’s path to its initial state at startup.
The re-initialized path is returned as an output.
See also: path, addpath, rmpath, genpath, pathdef, savepath, pathsep.
pathstr =
command_line_path ()
¶Return the path argument given to Octave at the command line when the
interpreter was started (--path arg
).
See also: path, addpath, rmpath, genpath, pathdef, savepath, pathsep.
dirname =
dir_in_loadpath (dir)
¶dirname =
dir_in_loadpath (dir, "all")
¶Return the absolute name of the loadpath element matching dir if it can
be found in the list of directories specified by path
.
If no match is found, return an empty character string.
The match is performed at the end of each path element. For example, if
dir is "foo/bar"
, it matches the path element
"/some/dir/foo/bar"
, but not
"/some/dir/foo/bar/baz"
"/some/dir/allfoo/bar"
. When dir is an absolute name,
rather than just a path fragment, it is matched against the file system
instead of Octave’s loadpath. In this case, if dir exists it will be
returned in dirname, otherwise an empty string is returned.
If the optional second argument is supplied, return a cell array containing all name matches rather than just the first.
See also: file_in_path, file_in_loadpath, path.
current_encoding =
dir_encoding (dir)
¶(dir, new_encoding)
¶(dir, "delete")
¶old_encoding =
dir_encoding (dir, new_encoding)
¶Query or set the encoding that is used for reading m-files in dir.
The per-directory encoding overrides the (globally set) m-file encoding.
The string DIR must match how the directory would appear in the load path.
The new_encoding input must be a valid encoding identifier or
"delete"
. In the latter case, any per-directory encoding is removed
and the (globally set) m-file encoding will be used for the given dir.
The currently or previously used encoding is returned only if an output argument is requested.
The directory encoding is automatically read from the file .oct-config
when a new path is added to the load path (for example with addpath
).
To set the encoding for all files in the same folder, that file must contain
a line starting with "encoding="
followed by the encoding identifier.
For example to set the file encoding for all files in the same folder to ISO 8859-1 (Latin-1), create a file .oct-config with the following content:
encoding=iso8859-1
If the file encoding is changed after the files have already been parsed, the
files have to be parsed again for that change to take effect. That can be done
with the command clear all
.
A function file may contain secondary functions called subfunctions. These secondary functions are only visible to the other functions in the same function file. For example, a file f.m containing
function f () printf ("in f, calling g\n"); g () endfunction function g () printf ("in g, calling h\n"); h () endfunction function h () printf ("in h\n") endfunction
defines a main function f
and two subfunctions. The
subfunctions g
and h
may only be called from the main
function f
or from the other subfunctions, but not from outside
the file f.m.
subfcn_list =
localfunctions ()
¶Return a list of all local functions, i.e., subfunctions, within the current file.
The return value is a column cell array of function handles to all local
functions accessible from the function from which localfunctions
is
called. Nested functions are not included in the list.
If the call is from the command line, an anonymous function, or a script, the return value is an empty cell array.
See also: functions.
In many cases one function needs to access one or more helper functions. If the helper function is limited to the scope of a single function, then subfunctions as discussed above might be used. However, if a single helper function is used by more than one function, then this is no longer possible. In this case the helper functions might be placed in a subdirectory, called "private", of the directory in which the functions needing access to this helper function are found.
As a simple example, consider a function func1
, that calls a helper
function func2
to do much of the work. For example:
function y = func1 (x) y = func2 (x); endfunction
Then if the path to func1
is <directory>/func1.m
, and if
func2
is found in the directory <directory>/private/func2.m
,
then func2
is only available for use of the functions, like
func1
, that are found in <directory>
.
Nested functions are similar to subfunctions in that only the main function is visible outside the file. However, they also allow for child functions to access the local variables in their parent function. This shared access mimics using a global variable to share information — but a global variable which is not visible to the rest of Octave. As a programming strategy, sharing data this way can create code which is difficult to maintain. It is recommended to use subfunctions in place of nested functions when possible.
As a simple example, consider a parent function foo
, that calls a nested
child function bar
, with a shared variable x.
function y = foo () x = 10; bar (); y = x; function bar () x = 20; endfunction endfunction foo () ⇒ 20
Notice that there is no special syntax for sharing x. This can lead to problems with accidental variable sharing between a parent function and its child. While normally variables are inherited, child function parameters and return values are local to the child function.
Now consider the function foobar
that uses variables x and
y. foobar
calls a nested function foo
which takes
x as a parameter and returns y. foo
then calls bat
which does some computation.
function z = foobar () x = 0; y = 0; z = foo (5); z += x + y; function y = foo (x) y = x + bat (); function z = bat () z = x; endfunction endfunction endfunction foobar () ⇒ 10
It is important to note that the x and y in foobar
remain
zero, as in foo
they are a return value and parameter respectively. The
x in bat
refers to the x in foo
.
Variable inheritance leads to a problem for eval
and scripts. If a
new variable is created in a parent function, it is not clear what should
happen in nested child functions. For example, consider a parent function
foo
with a nested child function bar
:
function y = foo (to_eval) bar (); eval (to_eval); function bar () eval ("x = 100;"); eval ("y = x;"); endfunction endfunction foo ("x = 5;") ⇒ error: can not add variable "x" to a static workspace foo ("y = 10;") ⇒ 10 foo ("") ⇒ 100
The parent function foo
is unable to create a new variable
x, but the child function bar
was successful. Furthermore, even
in an eval
statement y in bar
is the same y as in its
parent function foo
. The use of eval
in conjunction with nested
functions is best avoided.
As with subfunctions, only the first nested function in a file may be called from the outside. Inside a function the rules are more complicated. In general a nested function may call:
As a complex example consider a parent function ex_top
with two
child functions, ex_a
and ex_b
. In addition, ex_a
has two
more child functions, ex_aa
and ex_ab
. For example:
function ex_top () ## Can call: ex_top, ex_a, and ex_b ## Can NOT call: ex_aa and ex_ab function ex_a () ## Can call everything function ex_aa () ## Can call everything endfunction function ex_ab () ## Can call everything endfunction endfunction function ex_b () ## Can call: ex_top, ex_a, and ex_b ## Can NOT call: ex_aa and ex_ab endfunction endfunction
Functions can be overloaded to work with different input arguments. For
example, the operator ’+’ has been overloaded in Octave to work with single,
double, uint8, int32, and many other arguments. The preferred way to overload
functions is through classes and object oriented programming
(see Function Overloading). Occasionally, however, one needs to undo
user overloading and call the default function associated with a specific
type. The builtin
function exists for this purpose.
[…] =
builtin (f, …)
¶Call the base function f even if f is overloaded to another function for the given type signature.
This is normally useful when doing object-oriented programming and there is a requirement to call one of Octave’s base functions rather than the overloaded one of a new class.
A trivial example which redefines the sin
function to be the
cos
function shows how builtin
works.
sin (0) ⇒ 0 function y = sin (x), y = cos (x); endfunction sin (0) ⇒ 1 builtin ("sin", 0) ⇒ 0
A single dynamically linked file might define several functions. However, as Octave searches for functions based on the functions filename, Octave needs a manner in which to find each of the functions in the dynamically linked file. On operating systems that support symbolic links, it is possible to create a symbolic link to the original file for each of the functions which it contains.
However, there is at least one well known operating system that doesn’t
support symbolic links. Making copies of the original file for each of
the functions is undesirable as it increases the
amount of disk space used by Octave. Instead Octave supplies the
autoload
function, that permits the user to define in which
file a certain function will be found.
autoload_map =
autoload ()
¶(function, file)
¶(…, "remove")
¶Define function to autoload from file.
The second argument, file, should be an absolute filename or a file name in the same directory as the function or script from which the autoload command was run. file should not depend on the Octave load path.
Normally, calls to autoload
appear in PKG_ADD script files that are
evaluated when a directory is added to Octave’s load path. To avoid having
to hardcode directory names in file, if file is in the same
directory as the PKG_ADD script then
autoload ("foo", "bar.oct");
will load the function foo
from the file bar.oct
. The above
usage when bar.oct
is not in the same directory, or usages such as
autoload ("foo", file_in_loadpath ("bar.oct"))
are strongly discouraged, as their behavior may be unpredictable.
With no arguments, return a structure containing the current autoload map.
If a third argument "remove"
is given, the function is cleared and
not loaded anymore during the current Octave session.
See also: PKG_ADD.
It is sometime desirable to lock a function into memory with the mlock
function. This is typically used for dynamically linked functions in
oct-files or mex-files that contain some initialization, and it is desirable
that calling clear
does not remove this initialization.
As an example,
function my_function () mlock (); … endfunction
prevents my_function
from being removed from memory after it is called,
even if clear
is called. It is possible to determine if a function is
locked into memory with the mislocked
, and to unlock a function with
munlock
, which the following code illustrates.
my_function (); mislocked ("my_function") ⇒ ans = 1 munlock ("my_function"); mislocked ("my_function") ⇒ ans = 0
A common use of mlock
is to prevent persistent variables from being
removed from memory, as the following example shows:
function count_calls () mlock (); persistent calls = 0; printf ("count_calls() has been called %d times\n", ++calls); endfunction count_calls (); -| count_calls() has been called 1 times clear count_calls count_calls (); -| count_calls() has been called 2 times
mlock
might also be used to prevent changes to an m-file, such as in an
external editor, from having any effect in the current Octave session; A
similar effect can be had with the ignore_function_time_stamp
function.
()
¶Lock the current function into memory so that it can’t be removed with
clear
.
See also: munlock, mislocked, persistent, clear.
()
¶(fcn)
¶Unlock the named function fcn so that it may be removed from memory with
clear
.
If no function is named then unlock the current function.
See also: mlock, mislocked, persistent, clear.
tf =
mislocked ()
¶tf =
mislocked (fcn)
¶Return true if the named function fcn is locked in memory.
If no function is named then return true if the current function is locked.
See also: mlock, munlock, persistent, clear.
Given the numerous different ways that Octave can define a function, it is possible and even likely that multiple versions of a function, might be defined within a particular scope. The precedence of which function will be used within a particular scope is given by
numel
, size
,
etc.
A script file is a file containing (almost) any sequence of Octave commands. It is read and evaluated just as if you had typed each command at the Octave prompt, and provides a convenient way to perform a sequence of commands that do not logically belong inside a function.
Unlike a function file, a script file must not begin with the
keyword function
. If it does, Octave will assume that it is a
function file, and that it defines a single function that should be
evaluated as soon as it is defined.
A script file also differs from a function file in that the variables named in a script file are not local variables, but are in the same scope as the other variables that are visible on the command line.
Even though a script file may not begin with the function
keyword, it is possible to define more than one function in a single
script file and load (but not execute) all of them at once. To do
this, the first token in the file (ignoring comments and other white
space) must be something other than function
. If you have no
other statements to evaluate, you can use a statement that has no
effect, like this:
# Prevent Octave from thinking that this # is a function file: 1; # Define function one: function one () …
To have Octave read and com