Vdocument - in Octave Manual
Vdocument - in Octave Manual
diary on
opens a file called diary in your current working directory into which your following
octave commands along with prompts and results are saved or logged until you use
the octave command
diary off
Everything is saved into the file called diary from the statement following the diary
on command up to and including the diary off command.
You can also edit your diary file to add your name, course and assignment title. The
easiest way to edit in MathLab is to
0. find the file diary in the NeXT Workspace (clicking on the NeXT cube at the
top of the icon dock on the right) in the current working directory (likely your
home directory if you are just starting),
1. double click on the file name diary or its icon there, a NeXT Edit Window
should pop up
(if it does not, tell the lab assistant to correct the incorrect default,
directing the assistant to the Lab supervisor if the assistant does not
know),
lpr diary
(lpr means line printer, but these days should stand for laser printer; you can also use
what ever method you usually use in printing out files) from the command line (after
quitting octave) using the same the current working directory in the Terminal window
in which you typed the octave command.
The octave diary file custom naming command diary [filename] does work and will
just get you stuck.
If you have an existing diary file, you might want to erase (remove) it by the terminal
(unix) command
rm diary
mv diary diary.old
say, otherwise your new octave session will be added onto the old one.
History Command:
Your octave session or history is automatically saved to the file .octave_hist in your
home directory (~/.octave_hist) and the last 20 lines can be listed using the octave
command
history 20
history -q 35
lists the last 35 unnumbered, but in both cases NO octave prompts or octave outputs
are included.
Octave Example for Solving Set of Nonlinear
Equations
MathLab> octave
Octave, version 1.1.1.
Copyright (C) 1992, 1993, 1994, 1995 John W. Eaton.
This is free software with ABSOLUTELY NO WARRANTY.
For details, type `warranty'.
x = 1.7321
info = 1
x = -1
info = 1
info = 1
octave:5> # Comment: Solve System for Vector Root Starting at [1; 2]:
octave:5> [x, info] = fsolve ("f", [1; 2])
x=
0.57983
2.54621
info = 1
Quit:
octave:22> quit
MathLab>
Matrix Input:
octave:1> #
octave:1> # Sample Input of 4X4 Matrix with Rows Separated by Semicolons,
octave:1> # and elements in each row Separated by Commas:
octave:1> A=[0,2,0,1;2,2,3,2;4,-3,0,1.;6,1,-6,-5]
A=
0 2 0 1
2 2 3 2
4 -3 0 1
6 1 -6 -5
octave:2> #
octave:2> # Sample Input of Column Vector for Matrix Multiplication:
octave:2> B=[0;-2;-7;6]
B=
0
-2
-7
6
ans =
-0.50000
1.00000
0.33333
-2.00000
C=
octave:5> #
octave:5> # Still Another Example using "rand" to Get Test Vector:
octave:5> D=rand(5,1)
D=
0.8632258
0.2418298
0.0467658
0.3533209
0.0082342
ans =
5.49438
-1.02725
0.31745
3.55790
-8.52249
Matrix Norms:
octave:7> #
octave:7> # 'norm(A)' means 2-norm; else use norm(A,q) for q = 1, 2 or 'Inf':
octave:7> norm(C)
ans = 2.6476
octave:8> norm(C,2)
ans = 2.6476
octave:9> norm(C,1)
ans = 2.9868
octave:10> norm(C,Inf)
ans = 3.1385
Condition Numbers:
octave:11> #
octave:11> # Condition Number Examples, 2-norm assumed and singular values used:
octave:11> # 'cond(A)' allows no other norms and 'cond(A,1)' gives error!
octave:11> cond(A)
ans = 9.7626
octave:12> cond(C)
ans = 55.430
cond1A = 16.513
Determinants:
octave:14> #
octave:14> # Determinant Examples:
octave:14> det(A)
ans = -234
octave:15> det(C)
ans = -0.0073705
EigenValue Problems:
octave:16> #
octave:16> # Eigenvalue and Eigenvector Examples:
octave:16> # (Remark: For Long Output, Press "SPACE" when ":" for more?)
octave:16> [EVECT,EVAL]=eig(A)
EVECT =
Columns 1 through 3:
Column 4:
0.08069 + 0.07887i
-0.27971 - 0.17554i
-0.42233 + 0.43165i
0.71661 + 0.00000i
EVAL =
Columns 1 through 3:
Column 4:
0.00000 + 0.00000i
0.00000 + 0.00000i
0.00000 + 0.00000i
-1.17869 - 3.19871i
octave:17> #
octave:17> # (Remark: "eig(A)" alone give only eigenvalues in a column,
octave:17> # but "[Evect,Eval]=eig(A)" gives eigenvalues in a diagonal
octave:17> # array under the name "Eval" or chosen alias.)
octave:17> eig(C)
ans =
2.07361 + 0.00000i
0.08970 + 0.00000i
-0.66921 + 0.00000i
-0.13875 + 0.19989i
-0.13875 - 0.19989i
octave:18> [v,lambda]=eig(C)
v=
Columns 1 through 3:
Columns 4 and 5:
lambda =
Columns 1 through 3:
Columns 4 and 5:
LU Decomposition:
octave:19> #
octave:19> # LU Decomposition Examples:
octave:19> [L,U,P]=lu(A)
L=
U=
P=
0 0 0 1
0 0 1 0
0 1 0 0
1 0 0 0
octave:20> #
octave:20> # Note that P is the Pivot Permutation Matrix;
octave:20> # And if you use the short Form "lu(A)" you get a difficult
octave:20> # to understand Permuted LU Decomposition Answer:
octave:20> lu(A)
ans =
octave:21> [L,U,P]=lu(C)
L=
U=
P=
0 0 1 0 0
0 0 0 1 0
0 1 0 0 0
0 0 0 0 1
Quit:
octave:22> quit
MathLab>
Octave Quick Reference Octave Version 1.0 Killing and Yanking Strings and Common Escape Sequences
C-k kill to the end of the line A string constant consists of a sequence of characters enclosed
Starting Octave C-y yank the most recently killed text in either double-quote or single-quote marks.
octave start interactive Octave session M-d kill to the end of the current word a literal backslash
octave le run Octave on commands in le M-DEL kill the word behind the cursor " a literal double-quote character
octave --help describe command line options M-y rotate the kill ring and yank the new top ' a literal single-quote character
n newline, ASCII code 10
Stopping Octave Command Completion and History t horizontal tab, ASCII code 9
quit or exit exit Octave TAB complete a command or variable name
INTERRUPT e.g. C-c terminate current command M-? list possible completions Index Expressions
and return to top-level prompt RET enter the current line var idx select elements of a vector
C-p move `up' through the history list var idx1, idx2 select elements of a matrix
C-n move `down' through the history list
Getting Help M- move to the rst line in the history scalar select row column corresponding to
help list all commands and built-in variables M- move to the last line in the history
scalar
help command briey describe command vector select rows columns corresponding to the
C-r search backward in the history list elements of vector
help -i use Info to browse Octave manual C-s search forward in the history list
help -i command search for command in Octave manual range select rows columns corresponding to the
history -q N list N previous history lines, omitting elements of range
history numbers if -q : select all rows columns
Motion in Info history -w le write history to le .octave hist if no
SPC or C-v scroll forward one screenful
DEL or M-v scroll backward one screenful le argument Global Variables
history -r le read history from le .octave hist if global var1 ... Declare variables global.
C-l redraw the display
no le argument Global variables may be accessed inside the body of a
Node Selection in Info edit history lines edit and then run previous commands function without having to be passed in the function
from the history list parameter list provided they are also declared global within
n select the next node the function.
run history lines run previous commands from the history
p select the previous node
u select the `up' node list
t select the `top' node beg end Specify the rst and last history Selected Built-in Variables
commands to edit or run. EDITOR editor to use with edit history
d select the directory node If beg is greater than end, reverse the list of commands Inf, NaN IEEE innity, NaN
select the rst node in the current le before editing. If end is omitted, select commands from LOADPATH path to search for function les
select the last node in the current le beg to the end of the history list. If both arguments are PAGER program to use to paginate output
g reads the name of a node and selects it omitted, edit the previous item in the history list. ans last result not explicitly assigned
C-x k kills the current node eps machine precision
Shell Commands pi
Searching in Info cd dir change working directory to dir realmax maximum representable value
s search for a string realmin minimum representable value
pwd print working directory
C-s search forward incrementally
C-r search backward incrementally ls options print directory listing automatic replot automatically redraw plots
i search index & go to corresponding node getenv string return value of named environment do fortran indexing Fortran-style indexing of matrices
, go to next match from last `i' command variable implicit str to num ok allow strings to become numbers
shell cmd cmd execute arbitrary shell command string output max field width maximum numeric eld width
Command-Line Cursor Motion output precision min signicant gures displayed
page screen output control whether output is paged
C-b move back one character Matrices
Square brackets delimit literal matrices. Commas separate prefer column vectors create column vectors by default
C-f move forward one character
elements on the same row. Semicolons separate rows. Commas resize on range error automatic resizing of matrices
C-a move the the start of the line
may be replaced by spaces, and semicolons may be replaced by save precision digits stored by save command
C-e move to the end of the line
one or more newlines. Elements of a matrix may be arbitrary silent functions suppress output from functions
M-f move forward a word
expressions, provided that all the dimensions agree. warn divide by zero suppress divide by zero errors
M-b move backward a word
C-l clear screen, reprinting current line at top x, y, ... enter a row vector commas in literal matrix
x y ... enter a column vector control handling of spaces in matrices
Inserting or Changing Text w, x y, z enter a 2 2 matrix ignore function time stamp
M-TAB insert a tab character
DEL delete character to the left of the cursor ignore changes in function les during session
Ranges ok to lose imaginary part
C-d delete character under the cursor base : limit
C-v add the next character verbatim base : incr : limit allow complex to real conversion
C-t transpose characters at the point prefer zero one indexing
M-t transpose words at the point Specify a range of values beginning with base with no
elements greater than limit. If it is omitted, the default if ambiguous, prefer 0-1 style indexing
value of incr is 1. Negative increments are permitted.
surround optional arguments ... show one or more arguments
Copyright 1994, John W. Eaton Permissions on back
Arithmetic and Increment Operators Statements Linear Algebra
x+y addition for identier = expr stmt-list endfor chol a Cholesky factorization
x-y subtraction Execute stmt-list once for each column of expr. The det a compute the determinant of a matrix
x*y matrix multiplication variable identier is set to the value of the current column eig a eigenvalues and eigenvectors
x .* y element by element multiplication during each iteration. expm a compute the exponential of a matrix
xy right division, conceptually equivalent to hess a compute Hessenberg decomposition
inverse y' * x'' while
condition stmt-list endwhile inverse a invert a square matrix
x . y element by element right division Execute stmt-list while condition is true. norm , a p compute the p-norm of a matrix
x y left division, conceptually equivalent to pinv a compute pseudoinverse of a
inverse x * y break exit innermost loop qr
a compute the QR factorization of a matrix
x. y element by element left division continue go to beginning of innermost loop rank a matrix rank
x^y power operator return return to calling function schur a Schur decomposition of a matrix
x .^ y element by element power operator svd a singular value decomposition
- x negation if condition if-body else else-body endif syl , ,
a b c solve the Sylvester equation
+ x unary plus a no-op Execute if-body if condition is true, otherwise execute else-
x' complex conjugate transpose body. Equations, ODEs, DAEs, Quadrature
x .' transpose
++ x -- x increment decrement x, return new value if condition if-body elseif condition elseif-body endif *fsolve solve nonlinear algebraic equations
x ++ x -- increment decrement x, return old value Execute if-body if condition is true, otherwise execute the *lsode integrate nonlinear ODEs
elseif-body corresponding to the rst elseif condition that *dassl integrate nonlinear DAEs
is true, otherwise execute else-body. *quad integrate nonlinear functions
Assignment Expressions Any number of elseif clauses may appear in an if
var = expr assign expression to variable statement. perror nm, code for functions that return numeric codes,
var idx = expr assign expression to indexed variable print error message for named function
unwind protect body unwind protect cleanup cleanup end and given error code
Comparison and Boolean Operators Execute body. Execute cleanup no matter how control exits * See the on-line or printed manual for the complete list of
These operators work on an element-by-element basis. Both body. arguments for these functions.
arguments are always evaluated.
x y true if x is less than y Dening Functions Signal Processing
x =y true if x is less than or equal to y fft a Fast Fourier Transform using FFTPACK
x == y true if x is greater than y function ret-list function-name arg-list ifft a inverse FFT using FFTPACK
x =y true if x is greater than or equal to y function-body freqz args FIR lter frequency response
x y true if x is equal to y endfunction sinc x returns sin x x
x != y true if x is not equal to y
x&y true if both x and y are true ret-list may be a single identi er or a comma-separated list of Image Processing
x|y true if at least one of x or y is true identi ers delimited by square-brackets. colormap map set the current colormap
! bool true bool is false arg-list is a comma-separated list of identi ers and may be gray2ind , i n convert gray scale to Octave image
empty. image ,
img zoom display an Octave image matrix
Short-circuit Boolean Operators imagesc ,
img zoom display scaled matrix as image
Operators evaluate left-to-right, expecting scalar operands. Basic Matrix Manipulations
Operands are only evaluated if necessary, stopping once overall imshow ,
img map display Octave image
rows a return number of rows of a imshow , i n display gray scale image
truth value can be determined. Operands are converted to columns a return number of columns of a
scalars by applying the all function. imshow , , r g b display RGB image
all a check if all elements of a nonzero ind2gray ,
img map convert Octave image to gray scale
x && y true if both x and y are true any a check if any elements of a nonzero ind2rgb ,
img map convert indexed image to RGB
x || y true if at least one of x or y is true find a return indices of nonzero elements loadimage le load an image le
sort a order elements in each column of a rgb2ind , , r g b convert RGB to Octave image
Operator Precedence sum a sum elements in columns of a
prod a product of elements in columns of a saveimage , ,
le img fmt, map save a matrix to le
Here is a table of the operators in Octave, in order of
increasing precedence. min
args nd minimum values
max
args nd maximum values Sets
, statement separators create set , a b create row vector of unique values
rem ,
x y nd remainder of x y
= assignment, groups left to right complement , a b elements of b not in a
reshape , a m, n reformat a to be m by n
|| && logical or" and and" intersection , a b intersection of sets a and b
| & element-wise or" and and" union , a b union of sets a and b
diag ,
v k create diagonal matrices
= == = != relational operators
: colon linspace , ,
b l n create vector of linearly-spaced elements
+ - addition and subtraction logspace , ,
b l n create vector of log-spaced elements Strings
* .* . . multiplication and division eye ,
n m create n by m identity matrix strcmp , s t compare strings
' .' transpose ones ,
n m create n by m matrix of ones strcat , , ...s t concatenate strings
+ - ++ -- ! unary minus, increment, logical not" zeros ,
n m create n by m matrix of zeros
^ .^ exponentiation rand ,
n m create n by m matrix of random values
C-style Input and Output Basic Plotting
fopen ,
name mode open le name gplot ranges expr using title style 2D plotting
fclose
le close le
printf , ...
fmt formatted output to stdout gsplot ranges expr using title style 3D plotting
fprintf ,
le fmt , ...formatted output to le ranges specify data ranges
sprintf fmt, ... formatted output to string expr expression to plot
scanf
fmt formatted input from stdin using specify columns to plot
fscanf ,
le fmt formatted input from le title specify line title for legend
sscanf , str fmt formatted input from string style specify line style
fgets ,
le len read len characters from le If ranges are supplied, they must come before the expression
fflush
le ush pending output to le to plot. The using , title , and style options may appear in any
ftell
le return le pointer position order after expr . Multiple expressions may be plotted with a
frewind le move le pointer to beginning single command by separating them with commas.
freport print a info for open les set options set plotting options
fread , ,
le size prec read binary data les show options show plotting options
fwrite , ,
le size prec write binary data les replot redisplay current plot
feof
le determine if pointer is at EOF closeplot close stream to gnuplot process
A le may be referenced either by name or by the number purge tmp files clean up temporary plotting les
returned from fopen. Three les are preconnected when automatic replot built-in variable
Octave starts: stdin, stdout, and stderr.
Other Plotting Functions
Other Input and Output functions plot
args 2D plot with linear axes
save le var ... save variables in le semilogx
args 2D plot with logarithmic x-axis
load le load variables from le semilogy
args 2D plot with logarithmic y-axis
disp var display value of var to screen loglog
args 2D plot with logarithmic axes
bar
args plot bar charts
Miscellaneous Functions stairs ,
x y plot stairsteps
eval str evaluate str as a command hist ,
y x plot histograms
feval , ...
str evaluate function named by str, passing
remaining args to called function title string set plot title
error message print message and return to top level axis limits set axis ranges
xlabel string set x-axis label
clear pattern clear variables matching pattern ylabel string set y-axis label
exist str check existence of variable or function
who list current variables grid onjo set grid state
hold onjo set hold state
Polynomials ishold return 1 if hold is on, 0 otherwise
compan
p companion matrix
conv ,
a b convolution mesh , ,
x y z plot 3D surface
deconv ,
a b deconvolve two vectors meshdom ,
x y create mesh coordinate matrices
poly
a create polynomial from a matrix
polyderiv
p derivative of polynomial
polyreduce p integral of polynomial
polyval , p x value of polynomial at x
polyvalm , p x value of polynomial at x
roots p polynomial roots
residue , a b partial fraction expansion of ratio ab Edition 1.1 for Octave Version 1.1.0. Copyright 1994, 1995,
John W. Eaton [email protected] . The author assumes no
responsibility for any errors on this card.
Statistics
corrcoef , x y correlation coecient This card may be freely distributed under the terms of the GNU
cov ,
x y covariance General Public License.
mean
a mean value TEX Macros for this card by Roland Pesch [email protected] ,
median
a median value originally for the GDB reference card
std
a standard deviation
var
a variance Octave itself is free software you are welcome to distribute copies
of it under the terms of the GNU General Public License. There is
absolutely no warranty for Octave.
Octave
A high-level interactive language for numerical computations
Edition 1.1 for Octave version 1.1.0
January 1995
John W. Eaton
Copyright c 1993, 1994, 1995 John W. Eaton.
This is the rst edition of the Octave documentation, and is consistent with version 1.1.0 of Octave.
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 modi ed 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 same conditions as for modi ed versions.
Preface 1
Preface
Octave was originally intended to be companion software for an undergraduate-level textbook on
chemical reactor design being written by James B. Rawlings and John G. Ekerdt at the University
of Texas.
Clearly, Octave is now much more than just another `courseware' package with limited utiltiy
beyond the classroom. Although our initial goals were somewhat vague, we knew that we wanted
to create something that would enable students to solve realistic problems, and that they could use
for many things other than chemical reactor design problems.
There are those who would say that we should be teaching the students Fortran instead, because
that is the computer language of engineering, but every time we have tried that, the students have
spent far too much time trying to gure out why their Fortran code crashes and not enough time
learning about chemical engineering. With Octave, most students pick up the basics quickly, and
are using it condently in just a few hours.
Although it was originally intended to be used to teach reactor design, it is also currently used
in several other undergraduate and graduate courses in our department, and the math department
at the University of Texas has been using it for teaching di erential equations and linear algebra
as well. If you nd it useful, please let us know. We are always interested to nd out how Octave
is being used in other places.
Virtually everyone thinks that the name Octave has something to do with music, but it is ac-
tually the name of a former professor of mine who wrote a famous textbook on chemical reaction
engineering, and who was also well known for his ability to do quick `back of the envelope' calcu-
lations. 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 Copying , page 8 as described at the beginning of this manual. You are also
encouraged to help make Octave more useful by writing and contributing additional functions for
it, and by reporting any problems you may have.
Many people have already contributed to Octave's development. In addition to John W. Eaton,
the following people have helped write parts of Octave or helped out in various other ways.
Karl Berry [email protected] wrote the kpathsea library that allows Octave to recursively
search directory paths for function and script les.
Georg Beyerle [email protected] contributed code to save values in Matlab's `.mat'-
le format, and has provided many useful bug reports and suggestions.
John Campbell [email protected] wrote most of the le and C-style input and output func-
tions.
Brian Fox [email protected] wrote the readline library used for command history editing,
and the portion of this manual that documents it.
2 Octave
Preamble
The licenses for most software are designed to take away your freedom to share and change
it. By contrast, the GNU General Public License is intended to guarantee your freedom to share
and change free software|to make sure the software is free for all its users. This General Public
License applies to most of the Free Software Foundation's software and to any other program whose
authors commit to using it. Some other Free Software Foundation software is covered by the GNU
Library General Public License instead. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public
Licenses are designed to make sure that you have the freedom to distribute copies of free software
and charge for this service if you wish, that you receive source code or can get it if you want it,
that you can change the software or use pieces of it in new free programs and that you know you
can do these things.
To protect your rights, we need to make restrictions that forbid anyone to deny you these rights
or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you
if you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must
give the recipients all the rights that you have. You must make sure that they, too, receive or can
get the source code. And you must show them these terms so they know their rights.
We protect your rights with two steps: 1 copyright the software, and 2 oer you this license
which gives you legal permission to copy, distribute andor modify the software.
Also, for each author's protection and ours, we want to make certain that everyone understands
that there is no warranty for this free software. If the software is modied by someone else and
passed on, we want its recipients to know that what they have is not the original, so that any
problems introduced by others will not reect on the original authors' reputations.
Finally, any free program is threatened constantly by software patents. We wish to avoid the
danger that redistributors of a free program will individually obtain patent licenses, in eect making
the program proprietary. To prevent this, we have made it clear that any patent must be licensed
for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and modication follow.
4 Octave
separate works in themselves, then this License, and its terms, do not apply to those sections
when you distribute them as separate works. But when you distribute the same sections as
part of a whole which is a work based on the Program, the distribution of the whole must be
on the terms of this License, whose permissions for other licensees extend to the entire whole,
and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your rights to work written
entirely by you rather, the intent is to exercise the right to control the distribution of derivative
or collective works based on the Program.
In addition, mere aggregation of another work not based on the Program with the Program
or with a work based on the Program on a volume of a storage or distribution medium does
not bring the other work under the scope of this License.
3. You may copy and distribute the Program or a work based on it, under Section 2 in object
code or executable form under the terms of Sections 1 and 2 above provided that you also do
one of the following:
a. Accompany it with the complete corresponding machine-readable source code, which must
be distributed under the terms of Sections 1 and 2 above on a medium customarily used
for software interchange or,
b. Accompany it with a written o er, valid for at least three years, to give any third party, for
a charge no more than your cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be distributed under the terms
of Sections 1 and 2 above on a medium customarily used for software interchange or,
c. Accompany it with the information you received as to the o er to distribute corresponding
source code. This alternative is allowed only for noncommercial distribution and only if
you received the program in object code or executable form with such an o er, in accord
with Subsection b above.
The source code for a work means the preferred form of the work for making modications to
it. For an executable work, complete source code means all the source code for all modules
it contains, plus any associated interface denition les, plus the scripts used to control com-
pilation and installation of the executable. However, as a special exception, the source code
distributed need not include anything that is normally distributed in either source or binary
form with the major components compiler, kernel, and so on of the operating system on
which the executable runs, unless that component itself accompanies the executable.
If distribution of executable or object code is made by o ering access to copy from a designated
place, then o ering equivalent access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not compelled to copy the source
along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided
under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Pro-
gram is void, and will automatically terminate your rights under this License. However, parties
6 Octave
who have received copies, or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not signed it. However, nothing
else grants you permission to modify or distribute the Program or its derivative works. These
actions are prohibited by law if you do not accept this License. Therefore, by modifying or
distributing the Program or any work based on the Program, you indicate your acceptance
of this License to do so, and all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program or any work based on the Program, the recipient
automatically receives a license from the original licensor to copy, distribute or modify the
Program subject to these terms and conditions. You may not impose any further restrictions
on the recipients' exercise of the rights granted herein. You are not responsible for enforcing
compliance by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent infringement or for any other
reason not limited to patent issues, conditions are imposed on you whether by court order,
agreement or otherwise that contradict the conditions of this License, they do not excuse you
from the conditions of this License. If you cannot distribute so as to satisfy simultaneously
your obligations under this License and any other pertinent obligations, then as a consequence
you may not distribute the Program at all. For example, if a patent license would not permit
royalty-free redistribution of the Program by all those who receive copies directly or indirectly
through you, then the only way you could satisfy both it and this License would be to refrain
entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under any particular circumstance,
the balance of the section is intended to apply and the section as a whole is intended to apply
in other circumstances.
It is not the purpose of this section to induce you to infringe any patents or other property
right claims or to contest validity of any such claims this section has the sole purpose of
protecting the integrity of the free software distribution system, which is implemented by
public license practices. Many people have made generous contributions to the wide range of
software distributed through that system in reliance on consistent application of that system
it is up to the author donor to decide if he or she is willing to distribute software through any
other system and a licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a consequence of the
rest of this License.
8. If the distribution and or use of the Program is restricted in certain countries either by patents
or by copyrighted interfaces, the original copyright holder who places the Program under this
License may add an explicit geographical distribution limitation excluding those countries, so
that distribution is permitted only in or among countries not thus excluded. In such case, this
License incorporates the limitation as if written in the body of this License.
GNU GENERAL PUBLIC LICENSE 7
9. The Free Software Foundation may publish revised andor new versions of the General Public
License from time to time. Such new versions will be similar in spirit to the present version,
but may dier in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program species a version
number of this License which applies to it and any later version", you have the option of
following the terms and conditions either of that version or of any later version published
by the Free Software Foundation. If the Program does not specify a version number of this
License, you may choose any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free programs whose distribution
conditions are dierent, write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free Software Foundation we
sometimes make exceptions for this. Our decision will be guided by the two goals of preserving
the free status of all derivatives of our free software and of promoting the sharing and reuse of
software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WAR-
RANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS
ANDOR OTHER PARTIES PROVIDE THE PROGRAM AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFOR-
MANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DE-
FECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRIT-
ING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
ANDOR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO
YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CON-
SEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
PROGRAM INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES
OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS,
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSI-
BILITY OF SUCH DAMAGES.
You should have received a copy of the GNU General Public License
along with this program if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this when it starts in an interactive
mode:
Gnomovision version 69, Copyright C 19yy name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the
General Public License. Of course, the commands you use may be called something other than `show
w' and `show c' they could even be mouse-clicks or menu items|whatever suits your program.
You should also get your employer if you work as a programmer or your school, if any, to sign
a copyright disclaimer" for the program, if necessary. Here is a sample alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' which makes passes at compilers written by James Hacker.
signature of Ty Coon,
1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into proprietary pro-
grams. If your program is a subroutine library, you may consider it more useful to permit linking
GNU GENERAL PUBLIC LICENSE 9
proprietary applications with the library. If this is what you want to do, use the GNU Library
General Public License instead of this License.
10 Octave
Chapter 1: A Brief Introduction to Octave 11
Creating a Matrix
To create a new matrix and store it in a variable so that it you can refer to it later, type the
command
octave:1 a = 1, 1, 2 3, 5, 8 13, 21, 34
Octave will respond by printing the matrix in neatly aligned columns. Ending a command with a
semicolon tells Octave to not print the result of a command. For example
octave:2 b = rand 3, 2
will create a 3 row, 2 column matrix with each element set to a random value between zero and
one.
12 Octave
To display the value of any variable, simply type the name of the variable. For example, to
display the value stored in the matrix `b', type the command
octave:3 b
Matrix Arithmetic
Octave has a convenient operator notation for performing matrix arithmetic. For example, to
multiply the matrix a by a scalar value, type the command
octave:4 2 * a
To multiply the two matrices a and b, type the command
octave:5 a * b
To form the matrix product a
Ta , type the command
octave:6 a' * a
dt
= f x t with
x t = t0 = x0
For Octave to integrate equations of this form, you must rst provide a denition 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 dene the right hand side function for
an interesting pair of nonlinear di erential equations. Note that while you are entering a function,
Octave responds with a di erent prompt, to indicate that it is waiting for you to complete your
input.
octave:8 function xdot = f x, t
r = 0.25
k = 1.4
a = 1.5
b = 0.16
Chapter 1: A Brief Introduction to Octave 13
c = 0.9
d = 0.8
endfunction
and the set of output times as a column vector note that the rst output time corresponds to the
initial condition given above
t = linspace 0, 50, 200 '
The function `lsode' uses the Livermore Solver for Ordinary Dierential Equations, described in A.
C. Hindmarsh, ODEPACK, a Systematized Collection of ODE Solvers, in: Scientic Computing,
R. S. Stepleman et al. Eds., North-Holland, Amsterdam, 1983, pages 5564.
If you are using the X Window System, Octave will automatically create a separate window to
display the plot. If you are using a terminal that supports some other graphics commands, you will
need to tell Octave what kind of terminal you have. Type the command
set term
to see a list of the supported terminal types. Octave uses gnuplot to display graphics, and can
display graphics on any terminal that is supported by gnuplot.
To capture the output of the plot command in a le rather than sending the output directly to
your terminal, you can use a set of commands like this
set term postscript
set output "foo.ps"
replot
This will work for other types of output devices as well. Octave's `set' command is really just
piped to the gnuplot subprocess, so that once you have a plot on the screen that you like, you
should be able to do something like this to create an output le suitable for your graphics printer.
Or, you can eliminate the intermediate le by using commands like this
14 Octave
Getting Help
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 le.
In order to get good help you rst need to know the name of the command that you want to
use. This name of the function may not always be obvious, but a good place to start is to just
type help. This will show you all the operators, reserved words, functions, built-in variables, and
function les. You can then get more help on anything that is listed by simply including the name
as an argument to help. For example,
help plot
After making this le executable with the chmod command , you can simply type:
hello
at the shell, and the system will arrange to run Octave2 as if you had typed:
octave hello
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.
# usage: f x, t
1 The `#!' mechanism works on Unix systems derived from Berkeley Unix, System V Release 4,
and some System V Release 3 systems.
2 The line beginning with `#!' lists the full le name of an interpreter to be run, and an optional
initial command line argument to pass to that interpreter. The operating system then runs the
interpreter with the given argument and the full argument list of the executed program. The
rst argument in the list is the full le name of the Octave program. The rest of the argument
list will either be options to Octave, or data les, or both. The -qf option is usually speci ed
in stand-alone Octave programs to prevent them from printing the normal startup message,
and to keep them from behaving dierently depending on the contents of a particular user's
`~.octaverc' le. See Chapter 2 Invoking Octave, page 19.
16 Octave
#
# This function defines the right-hand-side functions for a set of
# nonlinear differential equations.
r = 0.25
and so on...
endfunction
The help command see Chapter 26 Help, page 151 is able to nd the rst block of comments
in a function even those that are composed directly on the command line . This means that users
of Octave can use the same commands to get help for built-in functions, and for functions that you
have de ned. For example, after de ning the function f above, the command
help f
produces the output
usage: f x, t
1.5 Errors
There are two classes of errors that Octave produces when it encounters input that it is unable
to understand, or when it is unable to perform an action.
A parse error occurs if Octave cannot understand something you have typed. For example, if
you misspell a keyword,
octave:13 functon y = f x y = x^2 endfunction
Octave will respond immediately with a message like this:
parse error:
Another class of error message occurs 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 denition, you
type
octave:13 f
This error message has several parts, and gives you quite a bit of information to help you locate
the source of the error. The messages are generated from the point of the innermost error, and
provide a traceback of enclosing expression and function calls.
In the example above, the rst line indicates that a variable named `x' was found to be undened
near line 1 and column 24 of some function or expression. For errors occurring within functions,
lines are numbered beginning with the line containing the `function' keyword. For errors occurring
at the top level, the line number indicates the input line number, which is usually displayed in the
prompt string.
The second and third lines in the example indicate that the error occurred within an assignment
expression, and the last line of the error message indicates that the error occurred within the
function `f'. If the function `f' had been called from another function, say `g', the list of errors
would have ended with one more line:
error: called from `g'
These lists of function calls usually make it fairly easy to trace the path your program took
before the error occurred, and to correct the error before trying again.
18 Octave
Chapter 2: Invoking Octave 19
2 Invoking Octave
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 le on the command line, and Octave will read and execute
the commands from the named le and then exit when it is nished.
You can further control how Octave starts up 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 brie y describe their use `octave -h' is a shorter equivalent.
--verbose
-V Turn on verbose output.
--version
-v Print the program version number and exit.
--echo-commands
-x Echo commands as they are executed.
le Execute commands from le.
3 Expressions
Expressions are the basic building block of statements in Octave. An expression evaluates to a
value, which you can print, test, store in a variable, pass to a function, or assign a new value to a
variable with an assignment operator.
An expression can serve as a statement on its own. Most other kinds of statements contain one
or more expressions which specify data to be operated on. As in other languages, expressions in
Octave include variables, array references, constants, and function calls, as well as combinations of
these with various operators.
parse error:
3 + 4 i
^
You may also use `j', `I', or `J' in place of the `i' above. All four forms are equivalent.
22 Octave
produces the string whose contents are `foobarbaz'. The next section explains more about how to
create matrices.
3.2 Matrices
It is easy to dene a matrix of values in Octave. The size of the matrix is determined automat-
ically, so it is not necessary to explicitly state the dimensions. The expression
a = 1, 2 3, 4
1 2
3 4
The commas which separate the elements on a row may be omitted, and the semicolon that
marks the beginning of a new row may be replaced by one or more new lines. The expression
a = 1 2
3 4
1 2 1 2
3 4 3 4
Inside the square brackets that delimit a matrix expression, Octave looks at the surrounding
context to determine whether spaces should be converted into element separators, or simply ignored,
so commands like
linspace 1, 2
will work. However, some possible sources of confusion remain. For example, in the expression
1 - 1
24 Octave
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 .
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 '
because to not do so would make it impossible to correctly parse the valid expression
a 'foo'
For clarity, it is probably best to always use commas and semicolons to separate matrix elements
and rows. It is possible to enforce this style by setting the built-in variable whitespace_in_
literal_matrix to "ignore". See Chapter 6 Built-in Variables , page 61.
By default, dimensions of the empty matrix are now printed along with the empty matrix
symbol, `'. For example:
octave:13 zeros 3, 0
ans =
3x0
Chapter 3: Expressions 25
The built-in variable print_empty_dimensions controls this behavior see Section 6.2 User
Preferences , page 62 .
Empty matrices may also be used in assignment statements as a convenient way to delete rows
or columns of matrices. See Section 3.13 Assignment Expressions , page 37.
3.3 Ranges
A range is a convenient way to write a row vector with evenly spaced elements. A range
constant is dened by the value of the rst 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
denes the set of values ` 1 2 3 4 5 ' the increment has been omitted, so it is taken as 1 , and
the range
1 : 3 : 5
denes the set of values ` 1 4 '. In this case, the base value is 1, the increment is 3, and the limit
is 5.
Although a range constant species a row vector, Octave does not convert range constants to
vectors unless it is necessary to do so. This allows you to write a constant like `1 : 10000' without
using up 80,000 bytes of storage on a typical 32-bit workstation.
Note that the upper or lower, if the increment is negative bound on the range is not always
included in the set of values, and that ranges dened by oating point values can produce surprising
results because Octave uses oating 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 Chapter 21 Special Matrices , page 133 .
3.4 Variables
Variables let you give names to values and refer to them later. You have already seen variables in
many of the examples. The name of a variable must be a sequence of letters, digits and underscores,
but it may not begin with a digit. Octave does not enforce a limit on the length of variable names,
but it is seldom useful to have variables with names longer than about 30 characters. The following
are all valid variable names
x
x15
__foo_bar_baz__
fucnrdthsucngtagdjb
26 Octave
Case is signicant 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. Vari-
ables are given new values with assignment operators and increment operators. See Section 3.13
Assignment Expressions , page 37.
A number of variables have special built-in meanings. For example, PWD holds the current
working directory, and pi names the ratio of the circumference of a circle to its diameter. See
Chapter 6 Built-in Variables , page 61, for a list of all the predened variables. Some of these
built-in symbols are constants and may not be changed. Others can be used and assigned just like
all other variables, but their values are also used or changed automatically by Octave.
Variables in Octave can be assigned either numeric or string values. Variables may not be used
before they have been given a value. Doing so results in an error.
a = 1, 2 3, 4
a 1, 1 , :
return the original matrix, or the matrix formed by selecting the rst row twice? Although this
con ict is not likely to arise very often in practice, you may select the behavior you prefer by setting
the built-in variable prefer_zero_one_indexing see Section 6.2 User Preferences, page 62.
Finally, indexing a scalar with a vector of ones can be used to create a vector the same size as
the the index vector, with each element equal to the value of the original scalar. For example, the
following statements
a = 13
a 1, 1, 1, 1
produce a vector whose four elements are all equal to 13.
Similarly, indexing a scalar with two vectors of ones can be used to create a matrix. For example
the following statements
a = 13
a 1, 1 , 1, 1, 1
create a 2 by 3 matrix with all elements equal to 13.
This is an obscure notation and should be avoided. It is better to use the function `ones' to
generate a matrix of the appropriate size whose elements are all one, and then to scale it to produce
the desired result. See Chapter 21 Special Matrices, page 133.
1 2
3 4
octave:4 x.c
x.c = string
Structures may be copied.
octave:1 y = x
y =
28 Octave
structure: a b c
Note that when the value of a structure is printed, Octave only displays the names of the
elements. This prevents long and confusing output from large deeply nested structures, but makes
it more dicult to view the values of simple structures, so this behavior may change in a future
version of Octave.
Since structures are themselves values, structure elements may reference other structures. The
following statements change the value of the element b of the structure x to be a data structure
containing the single element d, which has a value of 3.
octave:1 x.b.d = 3
x.b.d = 3
octave:2 x.b
x.b =
structure: d
octave:3 x.b.d
x.b.d = 3
Functions can return structures. For example, the following function separates the real and
complex parts of a matrix and stores them in two elements of the same structure variable.
octave:1 function y = f x
y.re = real x
y.im = imag x
endfunction
When called with a complex-valued argument, f returns the data structure containing the real
and imaginary parts of the original function argument.
octave:1 f rand 3 + rand 3 * I
ans =
structure: im re
octave:3 ans.im
ans.im =
octave:4 ans.re
ans.re =
Function return lists can include structure elements, and they may be indexed like any other
variable.
octave:1 x.u, x.s2:3,2:3 , x.v = svd 1, 2 3, 4
x.u =
-0.40455 -0.91451
-0.91451 0.40455
x.s =
x.v =
-0.57605 0.81742
-0.81742 -0.57605
octave:8 x
x =
structure: s u v
You can also use the function is_struct to determine whether a given value is a data structure.
For example
is_struct x
returns 1 if the value of the variable x is a data structure.
This feature should be considered experimental, but you should expect it to work. Suggestions
for ways to improve it are welcome.
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 dierent 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 eects, such as assigning the values of certain
variables or doing input or output operations.
Unlike most languages, functions in Octave may return multiple values. For example, the
following statement
u, s, v = svd a
computes the singular value decomposition of the matrix `a' and assigns the three result matrices
to `u', `s', and `v'.
The left side of a multiple assignment expression is itself a list of expressions, and is allowed to
be a list of variable names or index expressions. See also Section 3.5 Index Expressions , page 26,
and Section 3.13 Assignment Ops , page 37.
displays the value of the rst 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.
Chapter 3: Expressions 31
Call by value is also useful because it is always possible to pass constants for any function parameter
without rst 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".
3.7.2 Recursion
Recursive function calls are allowed. A recursive function is one which calls itself, either directly
or indirectly. For example, here is an ine cient1 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.
There is currently no limit on the recursion depth, so innite recursion is possible. If this
happens, Octave will consume more and more memory attempting to store intermediate values for
each function call context until there are no more resources available. This is obviously undesirable,
and will probably be xed in some future version of Octave by allowing users to specify a maximum
allowable recursion depth.
1
It would be much better to use prod 1:n, or gamma n+1 instead, after rst checking to
ensure that the value n is actually a positive integer.
32 Octave
global c = 3, d, e = 5
It is necessary declare a variable as global within a function body in order to access it. For
example,
global x
function f
x = 1
endfunction
f
does not set the value of the global variable `x' to 1. In order to change the value of the global
variable `x', you must also declare it to be global within the function body, like this
function f
global x
x = 1
endfunction
Passing a global variable in a function parameter list will make a local copy and not modify the
global value. For example:
octave:1 function f x
x = 3
endfunction
octave:2 global x = 0
octave:3 x # This is the value of the global variable.
x = 0
octave:4 f x
x = 3 # The value of the local variable x is 3.
octave:5 x # But it was a *copy* so the global variable
x = 0 # remains unchanged.
3.9 Keywords
The following identi ers are keywords, and may not be used as variable or function names:
break endfor function return
continue endfunction global while
else endif gplot
elseif endwhile gsplot
end for if
The following command-like functions are also keywords, and may not be used as variable or
function names:
casesen document history set
cd edit_history load show
clear help ls who
dir format run_history save
Chapter 3: Expressions 33
x .** y Element by element power operator. If both operands are matrices, the number of rows
and columns must both agree.
-x Negation.
+x Unary plus. This operator has no eect on the operand.
x' Complex conjugate transpose. For real arguments, this operator is the same as the
transpose operator. For complex arguments, this operator is equivalent to the expres-
sion
conj x.'
x.' Transpose.
Note that because Octave's element by element operators begin with a `.', there is a possible
ambiguity for statements like
1. m
because the period could be interpreted either as part of the constant or as part of the operator.
To resolve this con ict, 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.
1 0
0 1
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
x y True if x is not equal to y.
For matrix and vector arguments, the above table should be read as an element of the result
matrix vector is true if the corresponding elements of the argument matrices vectors satisfy the
speci ed condition"
String comparisons should be performed with the strcmp function, not with the comparison
operators listed above. See Section 3.7 Calling Functions, page 29.
! boolean
~ boolean Each element of the result is true if the corresponding element of boolean is false.
For matrix operands, these operators work on an element-by-element basis. For example, the
expression
1, 0 0, 1 & 1, 0 2, 3
returns a two by two identity matrix.
For the binary operators, the dimensions of the operands must conform if both are matrices. If
one of the operands is a scalar and the other a matrix, the operator is applied to the scalar and
each element of the matrix.
For the binary element-by-element boolean operators, both subexpressions boolean1 and
boolean2 are evaluated before computing the result. This can make a dierence when the ex-
pressions have side eects. 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.
3.12.2 Short-circuit Boolean Operators
Combined with the implicit conversion to scalar values in if and while conditions, Octave's
element-by-element boolean operators are often sucient 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 all boolean1 . If it is false, the result of the expression is
0. If it is true, the expression boolean2 is evaluated and converted to a scalar using
the equivalent of the operation all all boolean1 . If it is true, the result of the
expression is 1. Otherwise, the result of the expression is 0.
boolean1 || boolean2
The expression boolean1 is evaluated and converted to a scalar using the equivalent
of the operation all all boolean1 . If it is true, the result of the expression is
1. If it is false, the expression boolean2 is evaluated and converted to a scalar using
the equivalent of the operation all all boolean1 . If it is true, the result of the
expression is 1. Otherwise, the result of the expression is 0.
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
Chapter 3: Expressions 37
a && b++
instead of having to use two if statements to avoid attempting to evaluate an argument that
doesn't exist.
function f a, b, c
if nargin 2
if isstr c
...
After this expression is executed, the variable z has the value 1. Whatever old value z had
before the assignment is forgotten.
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
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 rst, 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.
Assigning an empty matrix ` ' works in most cases to allow you to delete rows or columns of
matrices and vectors. See Section 3.2.1 Empty Matrices , page 24. 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 rst, third, and fth 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, c, d = u, s, v = svd a
is equivalent to the expression above, except that the value of the variable `d' is left unchanged,
and the expression
a, b = u, s, v = svd a
is equivalent to
u, s, v = svd a
a = u
Chapter 3: Expressions 39
b = s
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.
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 rst, except
for the assignment, and exponentiation operators, which group in the opposite order. Thus, the
expression a - b + c groups as a - b + c, but the expression a = b = c groups as a = b = c.
The precedence of prex unary operators is important when another operator follows the
operand. For example, -x^2 means -x^2, because `-' has lower precedence than `^'.
Here is a table of the operators in Octave, in order of increasing precedence.
statement separators
` ', `,'.
assignment
`='. This operator groups right to left.
logical "or" and "and"
`||', `&&'.
element-wise "or" and "and"
`|', `&'.
relational
`', `=', `==', `=', `', `!=', `~=', `'.
colon `:'.
add, subtract
`+', `-'.
multiply, divide
`*', `', `', `.', `.*', `.'.
transpose
`'', `.''
unary plus, minus, increment, decrement, and ``not''
`+', `-', `++', `--', `!', `~'.
exponentiation
`^', `**', `.^', `.**'.
Chapter 4: Statements 41
4 Statements
Control statements such as if, while, and so on control the ow of execution in Octave pro-
grams. All the control statements start with special keywords such as if and while, to distinguish
them from simple expressions.
Many control statements contain other statements for example, the if statement contains
another statement which may or may not be executed. Each control statement has a corresponding
end statement that marks the end of the end of the control statement. For example, the keyword
endif marks the end of an if statement, and endwhile marks the end of a while statement. You
can use the keyword end anywhere a more speci c end keyword is expected, but using the more
speci c 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.
condition is an expression that controls what the rest of the statement will do. The then-body is
executed only if condition is true.
The condition in an if statement is considered true if its value is non-zero, and false if its value
is zero. If the value of the conditional expression in an if statement is a vector or a matrix, it is
considered true only if all of the elements are non-zero.
The second form of an if statement looks like this:
if condition then-body else else-body endif
In this example, if the expression rem x, 2 == 0 is true that is, the value of x is divisible by 2,
then the rst printf statement is evaluated, otherwise the second printf statement is evaluated.
42 Octave
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 satement.
In the following example, if the rst condition is true that is, the value of x is divisible by 2,
then the rst 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 rst 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 le, it may complain about missing or mismatched end statements, or, if you have not used
the more specic 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
Chapter 4: Statements 43
using the indentation to show how Octave groups the statements. See Chapter 5 Functions and
Scripts, page 49.
The assignment expression in the for statement works a bit dierently 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 either 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 rst 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 rst evaluating the expression `3:10', to produce a range of values from 3 to 10
inclusive. Then the variable i is assigned the rst 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.
In the for statement, body stands for any statement or list of statements.
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.
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 dn", num, div
else
printf "d is primen", num
endif
When the remainder is zero in the rst 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 di erent 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 dn", num, div
break
endif
div++
if div*div num
printf "d is primen", num
break
endif
endwhile
for x = vec
if rem x, 2 != 0
continue
endif
printf "dn", 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 rst 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 "dn", x
endif
endfor
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.
Chapter 4: Statements 47
This is useful to protect temporary changes to global variables from possible errors. For exam-
ple, the following code will always restore the original value of the built-in variable do_fortran_
indexing even if an error occurs while performing the indexing operation.
save_do_fortran_indexing = do_fortran_indexing
unwind_protect
do_fortran_indexing = "true"
elt = a idx
unwind_protect_cleanup
do_fortran_indexing = save_do_fortran_indexing
end_unwind_protect
Without unwind_protect, the value of do fortran indexing would not be restored if an error
occurs while performing the indexing operation because evaluation would stop at the point of the
error and the statement to restore the value would not be executed.
48 Octave
Chapter 5: Functions and Script Files 49
Complicated Octave programs can often be simplied by dening functions. Functions can be
dened directly on the command line during interactive Octave sessions, or in external les, and
can be called just like built-in ones.
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 rst argument to the printf statement.
In most cases, you will also want to get some information back from the functions you dene.
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 dened before the end of the function body in order for the
function to return a value.
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
and then called the function with a matrix instead of a vector as the argument, Octave would have
printed an error message like this:
error: `retval' undefined near line 1 column 10
error: evaluating index expression near line 7, column 1
because the body of the if statement was never executed, and retval was never dened. 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:
Chapter 5: Functions and Script Files 51
There is still one additional problem with this function. What if it is called without an argument?
Without additional error checking, Octave will probably print an error message that won't really
help you track down the source of the error. To allow you to catch errors like this, Octave provides
each function with an automatic variable called nargin. Each time a function is called, nargin is
automatically initialized to the number of arguments that have actually been passed to the function.
For example, we might rewrite the avg function like this:
function retval = avg v
retval = 0
if nargin != 1
error "usage: avg vector"
endif
if is_vector v
retval = sum v length v
else
error "avg: expecting vector argument"
endif
endfunction
Although Octave does not consider it an error if you call a function with more arguments than
were expected, doing so is probably an error, so we check for that possibility too, and issue the
error message if either too few or too many arguments have been provided.
The body of a user-de ned function can contain a return statement. This statement returns
control to the rest of the Octave program. A return statement is assumed at the end of every
function de nition.
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 rst occurrence in the vector.
function max, idx = vmax v
idx = 1
max = v idx
for i = 2:length v
if v i max
max = v i
idx = i
endif
endfor
endfunction
In this particular case, the two values could have been returned as elements of a single array,
but that is not always possible or convenient. The values to be returned may not have compatible
dimensions, and it is often desirable to give the individual return values distinct names.
In addition to setting nargin each time a function is called, Octave also automatically initializes
nargout to the number of values that are expected to be returned. This allows you to write
functions that behave dierently 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 gure in the count of
output arguments, so the value of nargout may be zero.
The svd and lu functions are examples of built-in functions that behave dierently depending
on the value of nargout.
It is possible to write functions that only set some return values. For example, calling the
function
function x, y, z = f
x = 1
z = 2
endfunction
as
a, b, c = f
produces:
a = 1
b = 0x0
Chapter 5: Functions and Script Files 53
c = 2
end
The keyword all_va_args always stands for the entire list of optional argument, so it is possible
to use it more than once within the same function without having to call var_start . It can
only be used within functions that take a variable number of arguments. It is an error to use it in
other contexts.
Each time vr_val is called, it places the value of its argument at the end of the list of values
to return from the function. Once vr_val has been called, there is no way to go back to the
beginning of the list and rewrite any of the return values.
As with variable argument lists, the ellipsis that marks the variable return list may only appear
once and must be the last element in the list of returned values.
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.
Chapter 5: Functions and Script Files 55
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.
Octave assumes that function les in the ` usr local lib octave 1.1.0' directory tree will
not change, so it doesn't have to check their time stamps every time the functions dened in those
les are used. This is normally a very good assumption and provides a signicant improvement in
performance for the function les that are distributed with Octave.
If you know that your own function les will not change while you are running Octave, you
can improve performance by setting the variable ignore_function_time_stamp to "all", so that
Octave will ignore the time stamps for all function les. Setting it to "system" gives the default
behavior. If you set it to anything else, Octave will check the time stamps on all function les.
function one
...
To have Octave read and compile these functions into an internal form, you need to make sure
that the le is in Octave's LOADPATH, then simply type the base name of the le that contains the
commands. Octave uses the same rules to search for script les as it does to search for function
les.
Chapter 5: Functions and Script Files 57
If the rst token in a le ignoring comments is function, Octave will compile the function
and try to execute it, printing a message warning about any non-whitespace characters that appear
after the function denition.
Note that Octave does not try to lookup the denition of any identier until it needs to evaluate
it. This means that Octave will compile the following statements if they appear in a script le, or
are typed at the command line,
# not a function file:
1
function foo
do_something
endfunction
function do_something
do_something_else
endfunction
even though the function do_something is not dened before it is referenced in the function foo.
This is not an error because the Octave does not need to resolve all symbols that are referenced by
a function until the function is actually evaluated.
Since Octave doesn't look for denitions until they are needed, the following code will always
print `bar = 3' whether it is typed directly on the command line, read from a script le, or is part
of a function body, even if there is a function or script le called `bar.m' in Octave's LOADPATH.
eval "bar = 3"
bar
Code like this appearing within a function body could fool Octave if denitions were resolved as
the function was being compiled. It would be virtually impossible to make Octave clever enough to
evaluate this code in a consistent fashion. The parser would have to be able to perform the `eval
' statement at compile time, and that would be impossible unless all the references in the string
to be evaluated could also be resolved, and requiring that would be too restrictive the string might
come from user input, or depend on things that are not known until the function is evaluated.
#include "defun-dld.h"
#include "tree-const.h"
Octave_object retval
cerr "Hello, world! n"
int nargin = args.length
for int i = 1 i nargin i++
retval nargin-i-1 = argsi .eval 1
return retval
If you would like to volunteer to help improve Octave's ability to dynamically link externally
compiled functions, please contact [email protected].
`linear-algebra'
Functions for linear algebra.
`miscellaneous'
Functions that don't really belong anywhere else.
`plot' A set of functions that implement the Matlab-like plotting functions.
`polynomial'
Functions for manipulating polynomials.
`set' Functions for creating and manipulating sets of unique values.
`signal' Functions for signal processing applications.
`specfun' Special functions.
`special-matrix'
Functions that create special matrix forms.
`startup' Octave's system-wide startup le.
`statistics'
Statistical functions.
`strings' Miscellaneous string-handling functions.
See Section 6.2 User Preferences , page 62 for an explanation of the built-in variable LOADPATH,
and Section 5.6 Function Files , page 55 for a description of the way Octave resolves unde ned
variable and function names.
60 Octave
Chapter 6: Built-in Variables 61
6 Built-in Variables
Most Octave variables are available for you to use for your own purposes they never change
except when your program assigns values to them, and never aect anything except when your
program examines them.
A few variables have special built-in meanings. Some of them, like pi and eps provide useful
prede ned constant values. Others, like do_fortran_indexing and page_screen_output are ex-
amined automatically by Octave, so that you can to tell Octave how to do certain things. There are
also two special variables, ans and PWD, that are set automatically by Octave and carry information
from the internal workings of Octave to your program.
This chapter documents all the built-in variables of Octave. Most of them are also documented
in the chapters that describe functions that use them, or are aected by their values.
realmin The smallest oating point number that is representable. The actual value is system-
dependent. On machines that support 64 bit IEEE oating point arithmetic, realmin
is approximately 2 2251 10 308 .
:
62 Octave
stdin
stdout
stderr These variables are the le numbers corresponding to the standard input, standard
output, and standard error streams. These streams are preconnected and available
when Octave starts.
OCTAVE_VERSION
The version number of Octave, as a string.
PAGER The default value is "less", or, if less is not available on your system, "more". See
Appendix A Installation , page 161, and Chapter 20 Input and Output , page 117.
PS1 The primary prompt string. When executing interactively, Octave displays the primary
prompt PS1 when it is ready to read a command. Octave allows the prompt to be
customized by inserting a number of backslash-escaped special characters that are
decoded as follows:
`t' The time.
`d' The date.
`n' Begins a new line by printing the equivalent of a carriage return followed
by a line feed.
`s' The name of the program usually just octave.
`w' The current working directory.
`W' The basename of the current working directory.
`u' The username of the current user.
`h' The hostname.
`#' The command number of this command, counting from when Octave starts.
`!' The history number of this command. This diers from `#' by the number
of commands in the history list when Octave starts.
`$' If the eective UID is 0, a #, otherwise a $.
`nnn' The character whose character code in octal is `nnn'.
`' A backslash.
The default value of PS1 is "s:# ". To change it, use a command like
octave:13 PS1 = "u@h "
which will result in the prompt `boris@kremvax ' for the user `boris' logged in on
the host `kremvax'. Note that two backslashes are required to enter a backslash into a
string. See Section 3.1.2 String Constants , page 22.
PS2 The secondary prompt string, which is printed when Octave is expecting additional
input to complete a command. For example, when dening a function over several
lines, Octave will print the value of PS1 at the beginning of each line after the rst.
Octave allows PS2 to be customized in the same way as PS1. The default value of PS2
is " ".
64 Octave
automatic_replot
If this variable is "true", Octave will automatically send a replot command to
gnuplot each time the plot changes. Since this is fairly inecient, the default value is
"false".
whitespace_in_literal_matrix
This variable allows some control over how Octave decides to convert spaces to commas
and semicolons in matrix expressions like `m 1' or
1, 2,
3, 4
If the value of whitespace_in_literal_matrix is "ignore", Octave will never insert
a comma or a semicolon in a literal matrix list. For example, the expression `1 2'
will result in an error instead of being treated the same as `1, 2', and the expression
1, 2,
3, 4
will result in the vector 1 2 3 4 instead of a matrix.
If the value of whitespace_in_literal_matrix is "traditional", Octave will convert
spaces to a comma between identi ers and `'. For example, given the matrix
m = 3 2
the expression
m 1
will be parsed as
m, 1
and will result in
3 2 1
and the expression
1, 2,
3, 4
will result in a matrix because the newline character is converted to a semicolon row
separator even though there is a comma at the end of the rst line trailing commas
or semicolons are ignored. This is apparently how Matlab behaves.
Any other value for whitespace_in_literal_matrix results in behavior that is the
same as traditional, except that Octave does not convert spaces to a comma between
identi ers and `'. For example, the expression
m 1
will produce `3'. This is the way Octave has always behaved.
default_save_format
do_fortran_indexing
If the value of do_fortran_indexing is "true", Octave allows you to select elements
of a two-dimensional matrix using a single index by treating the matrix as a single
vector created from the columns of the matrix. The default value is "false".
Chapter 6: Built-in Variables 65
empty_list_elements_ok
This variable controls whether Octave ignores empty matrices in a matrix list.
For example, if the value of empty_list_elements_ok is "true", Octave will ignore
the empty matrices in the expression
a = 1, , 3, , 5
and the variable `a' will be assigned the value ` 1 3 5 '.
The default value is "warn".
gnuplot_binary
The name of the program invoked by the plot command. The default value is
"gnuplot". See Appendix A Installation , page 161.
ignore_function_time_stamp
This variable variable can be used to prevent Octave from making the system call
stat each time it looks up functions de ned in function les. If ignore_function_
time_stamp to "system", Octave will not automatically recompile function les in
subdirectories of usr local lib 1.1.0 if they have changed since they were last
compiled, but will recompile other function les in the LOADPATH if they change. If
set to "all", Octave will not recompile any function les unless their de nitions are
removed with clear. For any other value of ignore_function_time_stamp, Octave
will always check to see if functions de ned in function les need to recompiled. The
default value of ignore_function_time_stamp is "system".
implicit_str_to_num_ok
If the value of implicit_str_to_num_ok is "true", implicit conversions of strings to
their numeric ASCII equivalents are allowed. Otherwise, an error message is printed
and control is returned to the top level. The default value is "false".
ok_to_lose_imaginary_part
If the value of ok_to_lose_imaginary_part is "true", implicit conversions of complex
numbers to real numbers are allowed for example, by fsolve. If the value is "warn",
the conversion is allowed, but a warning is printed. Otherwise, an error message is
printed and control is returned to the top level. The default value is "warn".
output_max_field_width
This variable speci es the maximum width of a numeric output eld. The default value
is 10.
It is possible to achieve a wide range of output styles by using dierent values of
output_precision and output_max_field_width. Reasonable combinations can be
set using the format function. See Section 20.1 Basic Input and Output , page 117.
output_precision
This variable speci es the minimum number of signi cant gures to display for numeric
output. The default value is 5.
66 Octave
print_empty_dimensions
If the value of print_empty_dimensions is "true", the dimensions of empty matrices
are printed along with the empty matrix symbol, ` '. For example, the expression
Chapter 6: Built-in Variables 67
zeros 3, 0
will print
ans =
3x0
propagate_empty_matrices
If the value of propagate_empty_matrices is "true", functions like inverse and svd
will return an empty matrix if they are given one as an argument. The default value
is "true". See Section 3.2.1 Empty Matrices , page 24.
resize_on_range_error
If the value of resize_on_range_error is "true", expressions like
for i = 1:10
a i = i
endfor
for `a' previously undened result in the variable `a' being resized to be just large
enough to hold the new value. Otherwise uninitialized elements are set to zero. If the
value of resize_on_range_error is "false", an error message is printed and control
is returned to the top level. The default value is "true".
return_last_computed_value
If the value of return_last_computed_value is true, and a function is dened with-
out explicitly specifying a return value, the function will return the value of the last
expression. Otherwise, no value will be returned. The default value is "false".
For example, the function
function f
2 + 2
endfunction
will either return nothing, if return_last_computed_value is "false", or 4, if it is
"true".
save_precision
This variable species the number of digits to keep when saving data with the save
command. The default value is 17.
silent_functions
If the value of silent_functions is "true", internal output from a function is sup-
pressed. Otherwise, the results of expressions within a function body that are not ter-
minated with a semicolon will have their values printed. The default value is "false".
For example, if the function
function f
2 + 2
endfunction
68 Octave
is executed, Octave will either print `ans = 4' or nothing depending on the value of
silent_functions.
split_long_rows
For large matrices, Octave may not be able to display all the columns of a given row
on one line of your screen. This can result in missing information or output that is
nearly impossible to decipher, depending on whether your terminal truncates or wraps
long lines.
If the value of split_long_rows is "true", Octave will display the matrix in a series
of smaller pieces, each of which can t within the limits of your terminal width. Each
set of rows is labeled so that you can easily see which columns are currently being
displayed. For example:
octave:13 rand 2, 9
ans =
Columns 1 through 7:
Columns 8 and 9:
0.08894 0.13266
0.28008 0.65575
The default value of split_long_rows is "true".
treat_neg_dim_as_zero
If the value of treat_neg_dim_as_zero is "true", expressions like
eye -1
produce an empty matrix i.e., row and column dimensions are zero . Otherwise, an
error message is printed and control is returned to the top level. The default value is
"false".
warn_assign_as_truth_value
If the value of warn_assign_as_truth_value is "true", a warning is issued for state-
ments like
if s = t
...
since such statements are not common, and it is likely that the intent was to write
if s == t
...
instead.
There are times when it is useful to write code that contains assignments within the
condition of a while or if statement. For example, statements like
Chapter 6: Built-in Variables 69
while c = getc
...
are common in C programming.
It is possible to avoid all warnings about such statements by setting warn_assign_as_
truth_value to "false", but that may also let real errors like
if x = 1 # intended to test x == 1!
...
slip by.
In such cases, it is possible suppress errors for specic statements by writing them with
an extra set of parentheses. For example, writing the previous example as
while c = getc
...
will prevent the warning from being printed for this statement, while allowing Octave
to warn about other assignments used in conditional contexts.
The default value of warn_assign_as_truth_value is "true".
warn_comma_in_global_decl
If the value of warn_comma_in_global_decl is "true", a warning is issued for state-
ments like
global a = 1, b
which makes the variables `a' and `b' global and assigns the value 1 to the variable `a',
because in this context, the comma is not interpreted as a statement separator.
The default value of warn_comma_in_global_decl is "true".
warn_divide_by_zero
If the value of warn_divide_by_zero is "true", a warning is issued when Octave
encounters a division by zero. If the value is "false", the warning is omitted. The
default value is "true".
7 Arithmetic
Unless otherwise noted, all of the functions described in this chapter will work for real and
complex scalar or matrix arguments.
floor x Return the largest integer not greater than x. If x is complex, return floor real
x + floor imag x * I.
fix x Truncate x toward zero. If x is complex, return fix real x + fix imag x *
I.
round x Return the integer nearest to x. If x is complex, return round real x + round
imag x * I.
signx = : 0 x =0
1 x 0.
For complex arguments, sign returns x . abs x .
exp x Compute the exponential of x. To compute the matrix exponential, see Chapter 8
Linear Algebra, page 75.
gcd x, ...
Compute the greatest common divisor of the elements of x, or the list of all the argu-
ments. For example,
gcd a1, ..., ak
is the same as
gcd a1, ..., ak
An optional second return value, v contains an integer vector such that
g = v1 * ak + ... + vk * ak
log x Compute the natural logarithm of x. To compute the matrix logarithm, see Chapter 8
Linear Algebra, page 75.
log2 x Compute the base-2 logarithm of x.
log10 x Compute the base-10 logarithm of x.
sqrt x Compute the square root of x. To compute the matrix square root, see Chapter 8
Linear Algebra, page 75.
max x For a vector argument, return the maximum value. For a matrix argument, return the
maximum value from each column, as a row vector. Thus,
max max x
returns the largest element of x.
For complex arguments, the magnitude of the elements are used for comparison.
min x Like max, but return the minimum value.
rem x, y
Return the remainder of x y, computed using the expression
x - y .* fix x . y
An error message is printed if the dimensions of the arguments do not agree, or if either
of the arguments is complex.
7.3 Trigonometry
Octave provides the following trigonometric functions:
sin asin sinh asinh
cos acos cosh acosh
tan atan tanh atanh
Chapter 7: Arithmetic 73
Each of these functions expect a single argument. For matrix arguments, they work on an element
by element basis. For example, the expression
sin 1, 2 3, 4
produces
ans =
0.84147 0.90930
0.14112 -0.75680
atan2 y, x
1 2
4 6
cumprod x
Return the cumulative product of each column of x. For example,
cumprod 1, 2 3, 4
produces
ans =
1 2
3 8
74 Octave
sumsq x For a vector argument, return the sum of the squares of all the elements. For a matrix
argument, return the sum of the squares of the elements in each column, as a row
vector.
a b = ab
a + b :
betai a, b, x
Returns the incomplete beta function,
Z x
a b x = a b 1
ta z
1 tb 1
dt:
0
If x has more than one component, both a and b must be scalars. If x is a scalar, a
and b must be of compatible dimensions.
erf Computes the error function,
Z z
erfz = p2 2
e t dt
0
gammai a, x
Computes the incomplete gamma function,
R x t a1
a x = 0 eta dt
If a is scalar, then gammai a, x is returned for each element of x and vice versa.
If neither a nor x is scalar, the sizes of a and x must agree, and gammai is applied
element-by-element.
lgamma Returns the natural logarithm of the gamma function.
Chapter 8: Linear Algebra 75
8 Linear Algebra
This chapter documents the linear algebra functions of Octave. Reference material for many
of these options may be found in Golub and Van Loan, Matrix Computations, 2nd Ed., Johns
Hopkins, 1989, and in LAPACK Users' Guide, SIAM, 1992.
The eigenvalues and eigenvectors of a matrix are computed in a several step process
which begins with a Hessenberg decomposition see hess, followed by a Schur decom-
position see schur, from which the eigenvalues are apparent. The eigenvectors, when
desired, are computed by further manipulations of the Schur decomposition.
See also: hess, schur.
givens
c, s = givens x, y
G = givens x, y
G = givensx, y returns a 2 2 orthogonal matrix G = c s -s' c such that G x
y = * 0 x, y scalars
inv a
inverse a
Compute the inverse of the square matrix a.
norm a, p
Compute the p-norm of the matrix a. If the second argument is missing, p=2 is
assumed.
If a is a matrix:
p=1 1-norm, the largest column sum of a.
p=2 Largest singular value of a.
p = Inf In nity norm, the largest row sum of a.
p = "fro"
Frobenius norm of a, sqrt sum diag a' * a.
If a is a vector or a scalar:
p = Inf max abs a.
pinv , X tol
Returns the pseudoinverse of X. Singular values less than tol are ignored.
If the second argument is omitted, it is assumed that
tol = max size X * sigma_max X * eps,
where sigma_max X is the maximal singular value of X.
rank , a tol
Compute the rank of a, using the singular value decomposition. The rank is taken to
be the number of singular values of a that are greater than the specied tolerance tol.
If the second argument is omitted, it is taken to be
tol = max size a * sigma 1 * eps
where eps is machine precision and sigma is the largest singular value of a.
trace a Compute the trace of a, sum diag a.
1.00000 0.00000
0.33333 1.00000
u =
3.00000 4.00000
0.00000 0.66667
78 Octave
p =
0 1
1 0
qr a Compute the QR factorization of a, using standard LAPACK subroutines. For example,
given the matrix a = 1, 2 3, 4 ,
q, r = qr a
returns
q =
-0.31623 -0.94868
-0.94868 0.31623
r =
-3.16228 -4.42719
0.00000 -0.63246
The qr factorization has applications in the solution of least squares problems
min
x
kAx bk2
for overdetermined systems of equations i.e., A is a tall, thin matrix. The qr factor-
ization is q * r = a where q is an orthogonal matrix and r is upper triangular.
The permuted qr factorization q, r, pi = qr a forms the qr factorization such
that the diagonal entries of r are decreasing in magnitude order. For example, given
the matrix a = 1, 2 3, 4 ,
q, r, pi = qra
returns
q =
-0.44721 -0.89443
-0.89443 0.44721
r =
-4.47214 -3.13050
0.00000 0.44721
p =
0 1
1 0
The permuted qr factorization q, r, pi = qr a factorization allows the construc-
tion of an orthogonal basis of span a.
Chapter 8: Linear Algebra 79
schur
u, s = schur a, opt opt = "a", "d", or "u"
s = schur a
The Schur decomposition is used to compute eigenvalues of a square matrix, and has
applications in the solution of algebraic Riccati equations in control see are and dare.
schur always returns S = U T AU where U is a unitary matrix U U is identity and S
0
is upper triangular. The eigenvalues of A and S are the diagonal elements of S If the
matrix A is real, then the real Schur decomposition is computed, in which the matrix
U is orthogonal and S is block upper triangular with blocks of size at most 2 2 blocks
along the diagonal. The diagonal elements of S or the eigenvalues of the 2 2 blocks,
when appropriate are the eigenvalues of A and S .
The eigenvalues are optionally ordered along the diagonal according to the value of
opt. opt = "a" indicates that all eigenvalues with negative real parts should be moved
to the leading block of S used in are, opt = "d" indicates that all eigenvalues with
magnitude less than one should be moved to the leading block of S used in dare,
and opt = "u", the default, indicates that no ordering of eigenvalues should occur. The
leading k columns of U always span the A-invariant subspace corresponding to the k
leading eigenvalues of S .
svd a Compute the singular value decomposition of a
A = U VH
The function svd normally returns the vector of singular values. If asked for three
return values, it computes U , S , and V . For example,
svd hilb 3
returns
ans =
1.4083189
0.1223271
0.0026873
and
u, s, v = svd hilb 3
returns
u =
s =
80 Octave
v =
The Taylor series is not the way to compute the matrix exponential see Moler and
Van Loan, Nineteen Dubious Ways to Compute the Exponential of a Matrix, SIAM
Review, 1978. This routine uses Ward's diagonal Pade approximation method with
three step preconditioning SIAM Journal on Numerical Analysis, 1977.
Diagonal Pade approximations are rational polynomials of matrices Dq a 1Nq a
whose Taylor series matches the rst 2q + 1 terms of the Taylor series above direct
evaluation of the Taylor series with the same preconditioning steps may be desirable
in lieu of the Pade approximation when Dq a is ill-conditioned.
logm a Compute the matrix logarithm of the square matrix a. Note that this is currently
implemented in terms of an eigenvalue expansion and needs to be improved to be more
robust.
sqrtm a Compute the matrix square root of the square matrix a. Note that this is currently
implemented in terms of an eigenvalue expansion and needs to be improved to be more
robust.
kron a, b
Form the kronecker product of two matrices, dened block by block as
x = ai, j b
qzhess a, b
Compute the Hessenberg-triangular decomposition of the matrix pencil a, b. This
function returns aa = q * a * z, bb = q * b * z, q, z orthogonal. For example,
Chapter 8: Linear Algebra 81
9 Polynomial Manipulations
In Octave, a polynomial is represented by its coecients arranged in descending order . For
example, a vector c of length n+1 corresponds to the following n-th order polynomial
px = c1 xn + ::: + cn x + cn+1 :
compan c
Compute the companion matrix corresponding to polynomial coecient vector c.
The companion matrix is
2
c2 =c1 c3 =c1 cn =c1 cn+1 =c1 3
66 1 0 0 0 7
7
6 7
A = 66 0
..
1 0
..
0
..
7
7 :
64 . ... . . 7
5
0 0 1 0
The eigenvalues of the companion matrix are equal to the roots of the polynomial.
conv a, b
Convolve two vectors.
y = conv a, b returns a vector of length equal to length a + length b - 1. If
a and b are polynomial coecient vectors, conv returns the coecients of the product
polynomial.
deconv y, a
Deconvolve two vectors.
b, r = deconv y, a solves for b and r such that y = conv a, b + r.
If y and a are polynomial coecient vectors, b will contain the coecients of the
polynomial quotient and r will be a remander polynomial of lowest order.
poly a If a is a square n-by-n matrix, poly a is the row vector of the coecients of det z *
eye n - a, the characteristic polynomial of a. If x is a vector, poly x is a vector
of coecients of the polynomial whose roots are the elements of x.
polyderiv c
Returns the coecients of the derivative of the polynomial whose coecients are given
by vector c.
polyinteg c
Returns the coecients of the integral the polynomial whose coecients are represented
by the vector c.
The constant of integration is set to zero.
84 Octave
polyreduce c
Reduces a polynomial coecient vector to a minimum number of terms by stripping
o any leading zeros.
c x
polyval ,
Evaluate a polynomial.
polyval c, x will evaluate the polynomial at the specied value of x.
If x is a vector or matrix, the polynomial is evaluated at each of the elements of x.
c x
polyvalm ,
Evaluate a polynomial in the matrix sense.
polyvalm c, x will evaluate the polynomial in the matrix sense, i.e. matrix multi-
plication is used instead of element by element multiplication as is used in polyval.
The argument x must be a square matrix.
b a tol
residue , ,
If b and a are vectors of polynomial coecients, then residue calculates the partial
fraction expansion corresponding to the ratio of the two polynomials.
The function residue returns r, p, k, and e, where the vector r contains the residue
terms, p contains the pole values, k contains the coecients of a direct polynomial
term if it exists and e is a vector containing the powers of the denominators in the
partial fraction terms.
Assuming b and a represent polynomials and P s we have: Q s
P s
=
XM r m
e +
XN n N n
k s :
pm m
Q s
m=1 s
n=1
where M is the number of poles the length of the r, p, and e vectors and N is the
length of the k vector.
The argument tol is optional, and if not specied, a default value of 0.001 is assumed.
The tolerance value is used to determine whether poles with small imaginary compo-
nents are declared real. It is also used to determine if two poles are distinct. If the
ratio of the imaginary part of a pole to the real part is less than tol, the imaginary part
is discarded. If two poles are farther apart than tol they are distinct. For example,
Example:
b = 1, 1, 1
a = 1, -5, 8, -4
p = 2, 2, 1
k = 0x0
e = 1, 2, 1
which implies the following partial fraction expansion
s2+s+1 = 2 + 7 + 3
s3 5s2 + 8s 4 s 2 s 2 2s 1
roots v
For a vector v with n components, return the roots of the polynomial
v1 z
n 1+ + vn + vn :
1z
86 Octave
Chapter 10: Nonlinear Equations 87
10 Nonlinear Equations
Octave can solve sets of nonlinear equations of the form
f x = 0
using the function fsolve, which is based on the MINPACK subroutine hybrd.
For example, to solve the set of equations
2x2 + 3xy + 4 siny 6 = 0
3x2 2xy2 + 3 cosx + 4 = 0
you rst need to write a function to compute the value of the given function. For example:
function y = f x
endfunction
Then, call fsolve with a specied initial condition to nd the roots of the system of equations.
For example, given the function f dened above,
x, info = fsolve "f", 1 2
results in the solution
x =
0.57983
2.54621
info = 1
A value of info = 1 indicates that the solution has converged.
The function perror may be used to print English messages corresponding to the numeric error
codes. For example,
perror "fsolve", 1
prints
solution converged to requested tolerance
Tolerances and other options for fsolve may be specied using the function fsolve_options.
88 Octave
Chapter 11: Dierential Equations 89
11 Dierential Equations
Octave has two built-in functions for solving dierential equations. Both are based on reliable
ODE solvers written in Fortran.
dt
= f x t
r = 0.25
k = 1.4
a = 1.5
b = 0.16
c = 0.9
d = 0.8
endfunction
is integrated with the command
x = lsode "f", 1 2, t = linspace 0, 50, 200'
90 Octave
producing a set of 200 values stored in the variable x. Note that this example takes advantage of
the fact that an assignment produces a value to store the values of the output times in the variable
t directly in the function call The results can then be plotted using the command
plot t, x
See Alan C. Hindmarsh, ODEPACK, A Systematized Collection of ODE Solvers, in Scientic
Computing, R. S. Stepleman, editor, 1983 for more information about this family of ODE solvers.
12 Optimization
12.1 Quadratic Programming
qpsol
x, obj, info, lambda
= qpsol x, H, c, lb, ub, lb, A, ub
Solve quadratic programs using Gill and Murray's QPSOL. Because QPSOL is not
freely redistributable, this function is only available if you have obtained your own
copy of QPSOL. See Appendix A Installation , page 161.
Tolerances and other options for qpsol may be speci ed using the function qpsol_options.
12.2 Nonlinear Programming
npsol
x, obj, info, lambda
= npsol x, 'phi', lb, ub, lb, A, ub, lb, 'g', ub
Solve nonlinear programs using Gill and Murray's NPSOL. Because NPSOL is not
freely redistributable, this function is only available if you have obtained your own
copy of NPSOL. See Appendix A Installation , page 161.
The second argument is a string containing the name of the objective function to call.
The objective function must be of the form
y = phi x
where x is a vector and y is a scalar.
Tolerances and other options for npsol may be speci ed using the function npsol_options.
Y X
ols ,
Ordinary Least Squares OLS estimation for the multivariate model
Y = X*B + E, mean E = 0, cov vec E = kron S, I
with
Y an T x p matrix
X an T x k matrix
B an k x p matrix
E an T x p matrix
Each row of Y and X is an observation and each column a variable.
Returns BETA, SIGMA, and R, where BETA is the OLS estimator for B, i.e.
BETA = pinvX*Y,
where pinvX denotes the pseudoinverse of X, SIGMA is the OLS estimator for the
matrix S, i.e.
SIGMA = Y - X*BETA'*Y - X*BETA T - rankX
and R = Y - X*BETA is the matrix of OLS residuals.
Chapter 13: Quadrature 93
13 Quadrature
14 Control Theory
abcddim a, b, c, d
Check for compatibility of the dimensions of the matrices dening the linear system
A, B, C, D corresponding to
dx = Ax + Bu
dt
y = Cx + Du
or a similar discrete-time system.
If the matrices are compatibly dimensioned, then abcddim returns n = number of
system states, m = number of system inputs, and p = number of system outputs.
Otherwise abcddim returns n = m = p = 1.
are a, b, c, opt
Returns the solution, x, of the algebraic Riccati equation
a' x + x a - x b x + c = 0
for identically dimensioned square matrices a, b, c. If b c is not square, then the
function attempts to use b*b' c '*c instead.
Solution method: apply Laub's Schur method IEEE Transactions on Automatic Con-
trol, 1979 to the appropriate Hamiltonian matrix.
opt is an option passed to the eigenvalue balancing routine. Default is "B".
c2d a, b, t
Converts the continuous time system described by:
dx = Ax + Bu
dt
into a discrete time equivalent model
xk+1 = Ad xk + Bd uk
via the matrix exponential assuming a zero-order hold on the input and sample time t.
dare a, b, c, r, opt
Returns the solution, x of the discrete-time algebraic Riccati equation
a' x a - x + a' x b r + b' x b^-1 b' x a + c = 0
for matrices with dimensions:
a: n by n
b: n by m
c : n by n, symmetric positive semidefinite
r : m by m, symmetric positive definite invertible
96 Octave
lqr a, b, q, r, z
k, p, e = lqr a, b, q, r, z
Linear quadratic regulator design for the continuous time system
dx = Ax + Bu
dt
to minimize the cost functional
Z 1 0
J= x Qx + u0Ru
0
z omitted or Z 1 0
J= x Qx + u0Ru + 2x0Zu
0
z included
Returns:
k is state feedback gain: A - B K is stable.
p is the stabilizing solution of appropriate algebraic Riccati equation.
e is the vector of the closed loop poles of A - B K.
lyap a, b, c
Solve the Lyapunov or Sylvester equation via the Bartels-Stewart algorithm Com-
munications of the ACM, 1972.
If a, b, c are specied, then lyap returns the solution of the Sylvester equation
a x + x b + c = 0
If only a, b are specied, then lyap returns the solution of the Lyapunov equation
a' x + x a + b = 0
If b is not square, then lyap returns the solution of either
a' x + x a + b' b = 0
or
Chapter 14: Control Theory 99
a x + x a' + b b' = 0
whichever is appropriate.
Solves by using the Bartels-Stewart algorithm 1972 .
tzero a, b, c, d, bal
Compute the transmission zeros of A, B, C, D.
bal = balancing option see balance default is "B".
Needs to incorporate mvzero algorithm to isolate nite zeros see Hodel, Computation
of System Zeros with Balancing, Linear Algebra and its Applications, July 1993.
100 Octave
Chapter 15: Signal Processing 101
15 Signal Processing
I hope that someday Octave will include more signal processing functions. If you would like to
help improve Octave in this area, please contact [email protected].
fft a Compute the FFT of a using subroutines from FFTPACK.
fft2 a Compute the two dimensional FFT of a.
fftconv a, b, N
This function returns the convolution of the vectors a and b, a vector with length
equal to the length a + length b - 1. If a and b are the coecient vectors of two
polynomials, the returned value is the coecient vector of the product polynomial.
The computation uses the FFT by calling the function fftfilt. If the optional argu-
ment N is speci ed, an N-point FFT is used.
fftfilt b, x, N
With two arguments, fftfilt lters x with the FIR lter b using the FFT.
Given the optional third argument, N, fftfilt uses the overlap-add method to lter
x with b using an N-point FFT.
filter b, a, x
This function returns the solution to the following linear, time-invariant di erence
equation:
X
N
k+1 n k
a y +
M X
k+1 n k = 0
b x 1 n P
k=0 k=0
where 2 N 1 , 2 M 1, and 2 P . An equivalent form of this equation is:
X X
a b x
N M
yn = k+1 n k
c y+ k+1 n k d x1 n P
k=1 k=0
where = 1 and = 1 .
c a=a d b=a
In terms of the z-transform, y is the result of passing the discrete- time signal x through
a system characterized by the following rational system function:
PM k+1 k
= k=0
P d z
1 + Nk+1 k+1 k
H z
c z
When called as
y, sf = filter b, a, x, si
filter uses the argument si as the initial state of the system and and returns the nal
state in sf. The state vector is a column vector whose length is equal to the length of
the longest coecient vector minus one. If si is not set, the initial state vector is set
to all zeros.
102 Octave
16 Sets
Octave has a limited set of functions for managing sets of data, where a set is dened as a
collection unique elements.
Given a matrix or vector of values, the function create_set returns a row vector containing
unique values, sorted in ascending order. For example, `create_set 1, 2 3, 4 4, 2 ' returns
the vector `1, 2, 3, 4 '.
The functions union and intersection take two sets as arguments and return the union and
interection, respectively. For example, `union 1, 2, 3 , 2, 3, 5 ' returns the vector `1, 2,
5 '.
The function complement a, b returns the elements of set b that are not in set a. For example,
`complement 1, 2, 3 , 2, 3, 5 ' returns the value `5'.
104 Octave
Chapter 17: Statistics 105
17 Statistics
I hope that someday Octave will include more statistics functions. If you would like to help
improve Octave in this area, please contact [email protected].
corrcoef x , y
If each row of x and y is an observation and each column is a variable, the i,j -th
entry of corrcoef x, y is the correlation between the i-th variable in x and the j-th
variable in y. If invoked with one argument, compute corrcoef x, x .
cov x , y
If each row of x and y is an observation and each column is a variable, the i,j -th entry
of cov x, y is the covariance between the i-th variable in X and the j-th variable in
y. If invoked with one argument, compute cov x, x .
kurtosis x
If x is a vector of length N, return the kurtosis
kurtosisx = N^-1 stdx ^-4 SUM_i xi -meanx ^4 - 3
of x. If x is a matrix, return the row vector containing the kurtosis of each column.
mahalanobis x, y
Returns Mahalanobis' D-square distance between the multivariate samples x and y,
which must have the same number of components columns , but may have a di erent
number of observations rows .
mean a If a is a vector, compute the mean of the elements of a. If a is a matrix, compute the
mean for each column and return them in a row vector.
median a
If a is a vector, compute the median value of the elements of a. If a is a matrix, compute
the median value for each column and return them in a row vector.
skewness x
If x is a vector of length N, return the skewness
skewness x = N^-1 stdx ^-3 SUM_i xi -meanx ^3
of x. If x is a matrix, return the row vector containing the skewness of each column.
std a If a is a vector, compute the standard deviation of the elements of a. If a is a matrix,
compute the standard deviation for each column and return them in a row vector.
106 Octave
Chapter 18: Plotting 107
18 Plotting
All of Octave's plotting functions use gnuplot to handle the actual graphics. There are two
low-level functions, gplot and gsplot, that behave almost exactly like the corresponding gnuplot
functions plot and `splot'. A number of other higher level plotting functions, patterned after the
graphics functions found in Matlab version 3.5, are also available. These higher level functions
are all implemented in terms of the two low-level plotting functions.
where the ranges, using, title, and style arguments are optional, and the using, title and style
qualiers may appear in any order after the expression. You may plot multiple expressions with
a single command by separating them with commas. Each expression may have its own set of
qualiers.
The optional item ranges has the syntax
x_lo : x_up y_lo : y_up
and may be used to specify the ranges for the axes of the plot, independent of the actual range
of the data. The range for the y axes and any of the individual limits may be omitted. A range
: indicates that the default limits should be used. This normally means that a range just large
enough to include all the data points will be used.
The expression to be plotted must not contain any literal matrices e.g. 1, 2 3, 4 since
it is nearly impossible to distinguish a plot range from a matrix of data.
See the help for gnuplot for a description of the syntax for the optional items.
By default, the gplot command plots the second column of a matrix versus the rst. If the
matrix only has one column, it is taken as a vector of y-coordinates and the x-coordinate is taken
as the element index, starting with zero. For example,
gplot rand 100,1 with linespoints
will plot 100 random values and connect them with lines. When gplot is used to plot a column
vector, the indices of the elements are taken as x values.
If there are more than two columns, you can choose which columns to plot with the using
qualier. For example, given the data
x = -10:0.1:10'
data = x, sin x, cos x
the command
gplot -11:11 -1.1:1.1 data with lines, data using 1:3 with impulses
108 Octave
will plot two lines. The rst line is generated by the command data with lines, and is a graph
of the sine function over the range -10 to 10. The data is taken from the rst two columns of the
matrix because columns to plot were not specied with the using qualier.
The clause using 1:3 in the second part of this plot command species that the rst and third
columns of the matrix data should be taken as the values to plot.
In this example, the ranges have been explicitly specied to be a bit larger than the actual range
of the data so that the curves do not touch the border of the plot.
In addition to the basic plotting commands, the whole range of set and show commands from
gnuplot are available, as is replot.
The set and show commands allow you to set and show gnuplot parameters. For more infor-
mation about the set and show commands, see the gnuplot user's guide also available on line if
you run gnuplot directly, instead of running it from Octave .
The replot command allows you to force the plot to be redisplayed. This is useful if you have
changed something about the plot, such as the title or axis labels. The replot command also
accepts the same arguments as gplot or gsplot except for data ranges so you can add additional
lines to existing plots.
For example,
set term tek40
set output "devplotter"
set title "sine with lines and cosine with impulses"
replot "sin x w l"
will change the terminal type for plotting, add a title to the current plot, add a graph of sin x
to the plot, and force the new plot to be sent to the plot device. This last step is normally required
in order to update the plot. This default is reasonable for slow terminals or hardcopy output devices
because even when you are adding additional lines with a replot command, gnuplot always redraws
the entire plot, and you probably don't want to have a completely new plot generated every time
something as minor as an axis label changes.
Since this may not matter as much on faster terminals, you can tell Octave to redisplay the plot
each time anything about it changes by setting the value of the builtin variable automatic_replot
to the value "true".
Note that NaN values in the plot data are automatically omitted, and Inf values are converted
to a very large value before calling gnuplot.
The Matlab-style two-dimensional plotting commands are:
plot args
This function produces two-dimensional plots. Many di erent combinations of argu-
ments are possible. The simplest form is
plot y
Chapter 18: Plotting 109
where the argument is taken as the set of y coordinates and the x coordinates are taken
to be the indices of the elements, starting with 1.
If more than one argument is given, they are interpreted as
plot x , y , fmt ...
where y and fmt are optional, and any number of argument sets may appear. The x
and y values are interpreted as follows:
If a single data argument is supplied, it is taken as the set of y coordinates and
the x coordinates are taken to be the indices of the elements, starting with 1.
If the rst argument is a vector and the second is a matrix, the the vector is
plotted versus the columns or rows of the matrix. using whichever combination
matches, with columns tried rst.
If the rst argument is a matrix and the second is a vector, the the columns or
rows of the matrix are plotted versus the vector. using whichever combination
matches, with columns tried rst.
If both arguments are vectors, the elements of y are plotted versus the elements
of x.
If both arguments are matrices, the columns of y are plotted versus the columns
of x. In this case, both matrices must have the same number of rows and columns
and no attempt is made to transpose the arguments to make the number of rows
match.
If both arguments are scalars, a single point is plotted.
The fmt argument, if present is intrepreted as follows. If fmt is missing, the default
gnuplot line style is assumed.
` -' Set lines plot style default .
`.' Set dots plot style.
`@' Set points plot style.
`-@' Set linespoints plot style.
` ^' Set impulses plot style.
`L' Set steps plot style.
`#' Set boxes plot style.
`~' Set errorbars plot style.
`#~' Set boxerrorbars plot style.
`n' Interpreted as the plot color if n is an integer in the range 1 to 6.
`nm' If nm is a two digit integer and m is an integer in the range 1 to 6, m is
interpreted as the point style. This is only valid in combination with the
@ or -@ speci ers.
110 Octave
`c' If c is one of "r", "g", "b", "m", "c", or "w", it is interpreted as the plot
color red, green, blue, magenta, cyan, or white.
` +'
` *'
` o'
` x' Used in combination with the points or linespoints styles, set the point
style.
The color line styles have the following meanings on terminals that support color.
Number Gnuplot colors linespoints style
1 red *
2 green +
3 blue o
4 magenta x
5 cyan house
6 brown there exists
Here are some plot examples:
plot x, y, "@12", x, y2, x, y3, "4", x, y4, "+"
This command will plot y with points of type 2 displayed as + and color 1 red, y2
with lines, y3 with lines of color 4 magenta and y4 with points displayed as +.
plot b, "*"
This command will plot the data in b will be plotted with points displayed as *.
hold Tell Octave to `hold' the current data on the plot when executing subsequent plotting
commands. This allows you to execute a series of plot commands and have all the lines
end up on the same gure. The default is for each new plot command to clear the plot
device rst. For example, the command
hold on
turns the hold state on. An argument of off turns the hold state o , and hold with
no arguments toggles the current hold state.
ishold Returns 1 if the next line will be added to the current plot, or 0 if the plot device will
be cleared before drawing the next line.
loglog args
Make a two-dimensional plot using log scales for both axes. See the description of plot
above for a description of the arguments that loglog will accept.
semilogx args
Make a two-dimensional plot using a log scale for the x axis. See the description of
plot above for a description of the arguments that semilogx will accept.
semilogy args
Make a two-dimensional plot using a log scale for the y axis. See the description of
plot above for a description of the arguments that semilogy will accept.
Chapter 18: Plotting 111
contour z, n, x, y
Make a contour plot of the three-dimensional surface described by z. Someone needs
to improve gnuplot's contour routines before this will be very useful.
polar theta, rho
Make a two-dimensional plot given polar the coordinates theta and rho.
18.2 Three-Dimensional Plotting
The syntax for Octave's three-dimensional plotting function, gsplot, is
gsplot ranges expression using title style
where the ranges, using, title, and style arguments are optional, and the using, title and style
quali ers may appear in any order after the expression. You may plot multiple expressions with
a single command by separating them with commas. Each expression may have its own set of
quali ers.
The optional item ranges has the syntax
x_lo : x_up y_lo : y_up z_lo : z_up
and may be used to specify the ranges for the axes of the plot, independent of the actual range of
the data. The range for the y and z axes and any of the individual limits may be omitted. A range
: indicates that the default limits should be used. This normally means that a range just large
enough to include all the data points will be used.
The expression to be plotted must not contain any literal matrices e.g. 1, 2 3, 4 since
it is nearly impossible to distinguish a plot range from a matrix of data.
See the help for gnuplot for a description of the syntax for the optional items.
By default, the gsplot command plots each column of the expression as the z value, using the
row index as the x value, and the column index as the y value. The indices are counted from zero,
not one. For example,
gsplot rand 5, 2
will plot a random surface, with the x and y values taken from the row and column indices of the
matrix.
If parametric plotting mode is set using the command `set parametric', then gsplot takes
the columns of the matrix three at a time as the x, y and z values that de ne a line in three space.
Any extra columns are ignored, and the x and y values are expected to be sorted. For example,
with `parametric' set, it makes sense to plot a matrix like
2 3
1 1 3 2 1 6 3 1 9
64 1 2 2 2 2 5 3 2 8 7 5
1 3 1 2 3 4 3 3 7
but not rand 5, 30.
112 Octave
xlabel string
ylabel string
Specify x and y axis labels for the plot. If you already have a plot displayed, use the
command replot to redisplay it with the new labels.
sombrero n
Display a classic three-dimensional mesh plot. The parameter n allows you to increase
the resolution.
clearplot
clg Clear the plot window and any titles or axis labels. The name clg is aliased to
clearplot for compatibility with Matlab.
The commands `gplot clear', `gsplot clear', and `replot clear' are equivalent to
`clearplot'. Previously, commands like `gplot clear' would evaluate `clear' as an
ordinary expression and clear all the visible variables.
closeplot
Close stream to the gnuplot subprocess. If you are using X11, this will close the plot
window.
purge_tmp_files
Delete the temporary les created by the plotting commands.
Octave creates temporary data les for gnuplot and then sends commands to gnuplot
through a pipe. Octave will delete the temporary les on exit, but if you are doing a
lot of plotting you may want to clean up in the middle of a session.
A future version of Octave will eliminate the need to use temporary les to hold the
plot data.
axis limits
Sets the axis limits for plots.
The argument limits should be a 2, 4, or 6 element vector. The rst and second elements
specify the lower and upper limits for the x axis. The second and third specify the
limits for the y axis, and the fourth and fth specify the limits for the z axis.
With no arguments, axis turns autoscaling on.
If your plot is already drawn, then you need to use replot before the new axis limits will
take eect. You can get this to happen automatically by setting the built-in variable
automatic_replot to "true". See Section 6.2 User Preferences, page 62.
hist y, x
Produce histogram counts or plots.
With one vector input argument, plot a histogram of the values with 10 bins. The
range of the histogram bins is determined by the range of the data.
Given a second scalar argument, use that as the number of bins.
114 Octave
Given a second vector argument, use that as the centers of the bins, with the width of
the bins determined from the adjacent values in the vector.
Extreme values are lumped in the rst and last bins.
With two output arguments, produce the values nn and xx such that bar xx, nn
will plot the histogram.
Chapter 19: Image Processing 115
19 Image Processing
To display images using these functions, you must be using Octave with the X Window System,
and you must have either xloadimage or xv installed. You do not need to be running X in order
to manipulate images, however, so some of these functions may be useful even if you are not able
to view the results.
colormap Set the current colormap.
colormap map sets the current colormap to map. The color map should be an n row
by 3 column matrix. The columns contain red, green, and blue intensities respectively.
All entries should be between 0 and 1 inclusive. The new colormap is returned.
colormap "default" restores the default colormap a gray scale colormap with 64
entries . The default colormap is returned.
With no arguments, colormap returns the current color map.
gray n Create a gray colormap with values from 0 to n. The argument n should be a scalar.
If it is omitted, 64 is assumed.
gray2ind Convert a gray scale intensity image to an Octave indexed image.
image Display an Octave image matrix.
image x displays a matrix as a color image. The elements of x are indices into the
current colormap and should have values between 1 and the length of the colormap.
image x, zoom changes the zoom factor. The default value is 4.
ind2rgb Convert an indexed image to red, green, and blue color components.
r, g, b = ind2rgb x uses the current colormap for the conversion.
r, g, b = ind2rgb x, map uses the specied colormap.
loadimage
Load an image le.
x, map = loadimage le loads an image and it's associated color map from the
specied le. The image must be stored in Octave's image format.
ocean n Create color colormap. The argument n should be a scalar. If it is omitted, 64 is
assumed.
rgb2ind Convert and RGB image to an Octave indexed image.
x, map = rgb2ind r, g, b
saveimage
Save a matrix to disk in image format.
saveimage le, x saves matrix x to le in Octave's image format. The current
colormap is also saved in the le.
saveimage le, x, "img" saves the image in the default format and is the same as
saveimage le, x .
saveimage le, x, "ppm" saves the image in ppm format instead of the default Oc-
tave image format.
saveimage le, x, "ps" saves the image in PostScript format instead of the default
Octave image format. Note: images saved in PostScript format can not be read back
into Octave with loadimage.
saveimage le, x, fmt, map saves the image along with the specied colormap in
the specied format.
Note: if the colormap contains only two entries and these entries are black and white,
the bitmap ppm and PostScript formats are used. If the image is a gray scale image the
entries within each row of the colormap are equal the gray scale ppm and PostScript
image formats are used, otherwise the full color formats are used.
Chapter 20: Input and Output 117
This works well as long as it is acceptable to have the name of the variable or `ans' printed
along with the value. To print the value of a variable without printing its name, use the function
disp. For example, the following expression
disp "The value of pi is:" , disp pi
will print
The value of pi is:
3.1416
Note that the output from disp always ends with a newline.
A simple way to control the output format is with the format statement. For example, to print
more digits for pi you can use the command
format long
118 Octave
long E
short E The same as `format long e' or `format short e' but always display output with an
uppercase `E' format. For example, with the `long E' format, pi is displayed as
3.14159265358979E+00
free
none Print output in free format, without trying to line up columns of matrices on the
decimal point. This also causes complex numbers to be formatted like this `0.604194,
0.607088' instead of like this `0.60419 + 0.60709i'.
bank Print in a xed format with two places to the right of the decimal point.
+ Print a `+' symbol for nonzero matrix elements and a space for zero matrix elements.
This format can be very useful for examining the structure of a large matrix.
The input function may be used for prompting the user for a value and storing the result in a
variable. For example,
input "Pick a number, any number! "
and waits for the user to enter a value. The string entered by the user is evaluated as an expression,
so it may be a literal constant, a variable name, or any other valid expression.
Chapter 20: Input and Output 119
Currently, input only returns one value, regardless of the number of values produced by the
evaluation of the expression.
If you are only interested in getting a literal string value, you can call input with the character
string `s' as the second argument. This tells Octave to return the string entered by the user directly,
without evaluating it rst.
Because there may be output waiting to be displayed by the pager, it is a good idea to always
call fflush stdout before calling input. This will ensure that all pending output is written to
the screen before your prompt. See Section 20.2 C-Style IO Functions, page 121.
The second input function, keyboard, is normally used for simple debugging. Using keyboard,
it is possible to examine the values of variables within a function, and to assign newassign new
variables Like input, it prompts the user for input, but no value is returned, and it continues to
prompt for input until the user types `quit', or `exit'.
If keyboard is invoked without any arguments, a default prompt of `debug ' is used.
For both of these functions, the normal command line history and editing functions are available
at the prompt.
To save variables in a le, use the save command. For example, the command
save data a b c
-binary Save the data in Octave's binary data format. Using this ag overrides the value of the
built-in variable default_save_precision
-float-binary
Save the data in Octave's binary data format but only using single precision. Using this
ag overrides the value of the built-in variable default_save_precision. You should
use this format only if you know that all the values to be saved can be represented in
single precision.
-mat-binary
Save the data in Matlab's binary data format. Using this ag overrides the value of
the built-in variable default_save_precision.
-save-builtins
Force Octave to save the values of built-in variables too. By default, Octave does not
save built-in variables.
Saving global variables also saves the global status of the variable, so that if it is restored at a
later time using `load', it will be restored as a global variable.
To restore the values from a le, use the load command. For example, to restore the variables
saved in the le `data', use the command
load data
Octave will refuse to overwrite existing variables unless you use the option `-force'.
If a variable that is not marked as global is loaded from a le when a global symbol with the
same name already exists, it is loaded in the global symbol table. Also, if a variable is marked as
global in a le and a local symbol exists, the local symbol is moved to the global symbol table and
given the value from the le. Since it seems that both of these cases are likely to be the result of
some sort of error, they will generate warnings.
As with save, you may specify a list of variables and load will only extract those variables with
names that match.
The load command can read data stored in Octave's text and binary formats, and Matlab's
binary format. It will automatically detect the type of le and do conversion from di erent oating
point formats currently only IEEE big and little endian, though other formats may added in the
future .
The following options may be speci ed for save.
-force Force variables currently in memory to be overwritten by variables with the same name
found in the le.
-ascii Force Octave to assume the le is in Octave's text format.
-binary Force Octave to assume the le is in Octave's binary format.
Chapter 20: Input and Output 121
-mat-binary
Force Octave to assume the le is in Matlab's binary format.
opens the le `splat.dat' for reading. Opening a le that is already open has no e ect.
The possible values `mode' may have are
`r' Open a text le for reading.
`w' Open a text le for writing. The previous contents are discared.
` a' Open or create a text le for writing at the end of the le.
`r+' Open an existing text le for reading and writing.
`w+' Open a text le for reading or writing. The previous contents are discared.
`a+' Open or create a text le for reading or writing at the end of the le.
122 Octave
To close a le once you are nished with it, use the function fclose le . If an error is encoun-
tered while trying to close the le, an error message is printed and fclose returns 0. Otherwise, it
returns 1.
20.2.2 Formatted Output
This section describes how to call printf and related functions.
The following functions are available for formatted output. They are modelled after the C
language functions of the same name.
printf template, ...
The printf function prints the optional arguments under the control of the template
string template to the stream stdout.
fprintf le, template, ...
This function is just like printf, except that the output is written to the stream le
instead of stdout.
sprintf template, ...
This is like printf, except that the output is written to a string. Unlike the C library
function, which requires you to provide a suitably sized string as an argument, Oc-
tave's sprintf function returns the string, automatically sized to hold all of the items
converted.
The printf function can be used to print any number of arguments. The template string argu-
ment you supply in a call provides information not only about the number of additional arguments,
but also about their types and what style should be used for printing them.
Ordinary characters in the template string are simply written to the output stream as-is, while
conversion speci cations introduced by a `' character in the template cause subsequent arguments
to be formatted and written to the output stream. For example,
pct = 37
filename = "foo.txt"
printf "Processing of `s' is d finished. nPlease be patient. n",
filename, pct
This example shows the use of the `d' conversion to specify that a scalar argument should be
printed in decimal notation, the `s' conversion to specify printing of a string argument, and the
`' conversion to print a literal `' character.
There are also conversions for printing an integer argument as an unsigned value in octal,
decimal, or hexadecimal radix `o', `u', or `x', respectively or as a character value `c' .
Chapter 20: Input and Output 123
Floating-point numbers can be printed in normal, xed-point notation using the ` f' conversion
or in exponential notation using the ` e' conversion. The ` g' conversion uses either ` e' or ` f'
format, depending on what is more appropriate for the magnitude of the particular number.
You can control formatting more precisely by writing modiers between the ` ' and the char-
acter that indicates which conversion to apply. These slightly alter the ordinary behavior of the
conversion. For example, most conversion speci cations permit you to specify a minimum eld
width and a ag indicating whether you want the result left- or right-justi ed within the eld.
The speci c ags and modi ers that are permitted and their interpretation vary depending on
the particular conversion. They're all described in more detail in the following sections.
You can also specify a precision of `*'. This means that the next argument in the argument list
before the actual value to be printed is used as the precision. The value must be an integer,
and is ignored if it is negative.
An optional type modier character. This character is ignored by Octave's printf function,
but is recognized to provide compatibility with the C language printf.
A character that speci es the conversion to be applied.
The exact options that are permitted and how they are interpreted vary between the di erent
conversion speci ers. See the descriptions of the individual conversions for information about the
particular options that they use.
20.2.4 Table of Output Conversions
Here is a table summarizing what all the di erent conversions do:
`d', `i' Print an integer as a signed decimal number. See Section 20.2.5 Integer Conversions,
page 125, for details. `d' and `i' are synonymous for output, but are di erent when
used with scanf for input see Section 20.2.10 Table of Input Conversions, page 128.
`o' Print an integer as an unsigned octal number. See Section 20.2.5 Integer Conversions,
page 125, for details.
`u' Print an integer as an unsigned decimal number. See Section 20.2.5 Integer Conver-
sions, page 125, for details.
`x', `X' Print an integer as an unsigned hexadecimal number. `x' uses lower-case letters and
`X' uses upper-case. See Section 20.2.5 Integer Conversions, page 125, for details.
`f' Print a oating-point number in normal xed-point notation. See Section 20.2.6
Floating-Point Conversions, page 125, for details.
`e', `E' Print a oating-point number in exponential notation. `e' uses lower-case letters and
`E' uses upper-case. See Section 20.2.6 Floating-Point Conversions, page 125, for
details.
`g', `G' Print a oating-point number in either normal or exponential notation, whichever is
more appropriate for its magnitude. `g' uses lower-case letters and `G' uses upper-
case. See Section 20.2.6 Floating-Point Conversions, page 125, for details.
`c' Print a single character. See Section 20.2.7 Other Output Conversions, page 126.
`s' Print a string. See Section 20.2.7 Other Output Conversions, page 126.
`' Print a literal `' character. See Section 20.2.7 Other Output Conversions, page 126.
If the syntax of a conversion speci cation is invalid, unpredictable things will happen, so don't
do this. If there aren't enough function arguments provided to supply values for all the conversion
speci cations in the template string, or if the arguments are not of the correct types, the results are
Chapter 20: Input and Output 125
unpredictable. If you supply more arguments than conversion specications, the extra argument
values are simply ignored this is sometimes useful.
20.2.5 Integer Conversions
This section describes the options for the ` d', ` i', ` o', ` u', ` x', and ` X' conversion speci-
cations. These conversions print integers in various formats.
The ` d' and ` i' conversion specications both print an numeric argument as a signed decimal
number while ` o', ` u', and ` x' print the argument as an unsigned octal, decimal, or hexadecimal
number respectively. The ` X' conversion specication is just like ` x' except that it uses the
characters `ABCDEF' as digits instead of `abcdef'.
The following ags are meaningful:
`- ' Left-justify the result in the eld instead of the normal right-justication.
` +' For the signed ` d' and ` i' conversions, print a plus sign if the value is positive.
`' For the signed ` d' and ` i' conversions, if the result doesn't start with a plus or minus
sign, prex it with a space character instead. Since the `+' ag ensures that the result
includes a sign, this ag is ignored if you supply both of them.
` #' For the ` o' conversion, this forces the leading digit to be `0', as if by increasing the
precision. For ` x' or ` X', this prexes a leading `0x' or `0X' respectively to the result.
This doesn't do anything useful for the ` d', ` i', or ` u' conversions.
`0 ' Pad the eld with zeros instead of spaces. The zeros are placed after any indication
of sign or base. This ag is ignored if the `-' ag is also specied, or if a precision is
specied.
If a precision is supplied, it species the minimum number of digits to appear leading zeros are
produced if necessary. If you don't specify a precision, the number is printed with as many digits
as it needs. If you convert a value of zero with an explicit precision of zero, then no characters at
all are produced.
20.2.6 Floating-Point Conversions
This section discusses the conversion specications for oating-point numbers: the ` f', ` e',
` E', ` g', and ` G' conversions.
The ` f' conversion prints its argument in xed-point notation, producing output of the form
-ddd.ddd, where the number of digits following the decimal point is controlled by the precision
you specify.
The ` e' conversion prints its argument in exponential notation, producing output of the form
-d.ddde+|-dd. Again, the number of digits following the decimal point is controlled by the
126 Octave
precision. The exponent always contains at least two digits. The ` E' conversion is similar but the
exponent is marked with the letter `E' instead of `e'.
The ` g' and ` G' conversions print the argument in the style of ` e' or ` E' respectively if the
exponent would be less than -4 or greater than or equal to the precision otherwise they use the
` f' style. Trailing zeros are removed from the fractional portion of the result and a decimal-point
character appears only if it is followed by a digit.
The following ags can be used to modify the behavior:
`- ' Left-justify the result in the eld. Normally the result is right-justied.
`+ ' Always include a plus or minus sign in the result.
`' If the result doesn't start with a plus or minus sign, prex it with a space instead. Since
the `+' ag ensures that the result includes a sign, this ag is ignored if you supply
both of them.
` #' Species that the result should always include a decimal point, even if no digits follow
it. For the ` g' and ` G' conversions, this also forces trailing zeros after the decimal
point to be left in place where they would otherwise be removed.
` 0' Pad the eld with zeros instead of spaces the zeros are placed after any sign. This ag
is ignored if the `-' ag is also specied.
The precision species how many digits follow the decimal-point character for the ` f', ` e', and
` E' conversions. For these conversions, the default precision is 6. If the precision is explicitly 0,
this suppresses the decimal point character entirely. For the ` g' and ` G' conversions, the precision
species how many signicant digits to print. Signicant digits are the rst digit before the decimal
point, and all the digits after it. If the precision is 0 or not specied for ` g' or ` G', it is treated
like a value of 1. If the value being printed cannot be expressed precisely in the specied number
of digits, the value is rounded to the nearest number that ts.
20.2.7 Other Output Conversions
This section describes miscellaneous conversions for printf.
The ` c' conversion prints a single character. The `-' ag can be used to specify left-justication
in the eld, but no other ags are dened, and no precision or type modier can be given. For
example:
printf " c c c c c", "h", "e", "l", "l", "o"
prints `hello'.
The ` s' conversion prints a string. The corresponding argument must be a string. A precision
can be specied to indicate the maximum number of characters to write otherwise characters in
the string up to but not including the terminating null character are written to the output stream.
Chapter 20: Input and Output 127
The `-' ag can be used to specify left-justi cation in the eld, but no other ags or type modi ers
are de ned for this conversion. For example:
printf "3s-6s", "no", "where"
prints ` nowhere '.
20.2.8 Formatted Input
Here are the descriptions of the functions for performing formatted input.
scanf template
The scanf function reads formatted input from the stream stdin under the control of
the template string template. The resulting values are returned.
fscanf le, template
This function is just like scanf, except that the input is read from the stream le
instead of stdin.
sscanf string, template
This is like scanf, except that the characters are taken from the string string instead
of from a stream. Reaching the end of the string is treated as an end-of- le condition.
Calls to scanf are super cially similar to calls to printf in that arbitrary arguments are read
under the control of a template string. While the syntax of the conversion speci cations in the
template is very similar to that for printf, the interpretation of the template is oriented more
towards free-format input and simple pattern matching, rather than xed- eld formatting. For
example, most scanf conversions skip over any amount of white space" including spaces, tabs,
and newlines in the input le, and there is no concept of precision for the numeric input conversions
as there is for the corresponding output conversions. Ordinarily, non-whitespace characters in the
template are expected to match characters in the input stream exactly.
When a matching failure occurs, scanf returns immediately, leaving the rst non-matching
character as the next character to be read from the stream, and scanf returns all the items that
were successfully converted.
The formatted input functions are not used as frequently as the formatted output functions.
Partly, this is because it takes some care to use them properly. Another reason is that it is dicult
to recover from a matching error.
20.2.9 Input Conversion Syntax
A scanf template string is a string that contains ordinary multibyte characters interspersed
with conversion speci cations that start with `'.
Any whitespace character in the template causes any number of whitespace characters in the
input stream to be read and discarded. The whitespace characters that are matched need not be
128 Octave
exactly the same whitespace characters that appear in the template string. For example, write ` ,
' in the template to recognize a comma with optional whitespace before and after.
Other characters in the template string that are not part of conversion specications must match
characters in the input stream exactly if this is not the case, a matching failure occurs.
The conversion specications in a scanf template string have the general form:
ags width type conversion
In more detail, an input conversion specication consists of an initial `' character followed in
sequence by:
An optional ag character `*', which says to ignore the text read for this specication. When
scanf nds a conversion specication that uses this ag, it reads input as directed by the rest
of the conversion specication, but it discards this input, does not use a pointer argument, and
does not increment the count of successful assignments.
An optional decimal integer that species the maximum eld width. Reading of characters from
the input stream stops either when this maximum is reached or when a non-matching character
is found, whichever happens rst. Most conversions discard initial whitespace characters those
that don't are explicitly documented, and these discarded characters don't count towards the
maximum eld width.
An optional type modier character. This character is ignored by Octave's scanf function,
but is recognized to provide compatibility with the C language scanf.
A character that species the conversion to be applied.
The exact options that are permitted and how they are interpreted vary between the dierent
conversion speciers. See the descriptions of the individual conversions for information about the
particular options that they allow.
` x', ` X' Matches an unsigned integer written in hexadecimal radix. See Section 20.2.11 Nu-
meric Input Conversions , page 129.
` e', ` f', ` g', ` E', ` G'
Matches an optionally signed oating-point number. See Section 20.2.11 Numeric
Input Conversions , page 129.
` s' Matches a string containing only non-whitespace characters. See Section 20.2.12 String
Input Conversions , page 129.
` c' Matches a string of one or more characters the number of characters read is controlled
by the maximum eld width given for the conversion. See Section 20.2.12 String Input
Conversions , page 129.
` ' This matches a literal ` ' character in the input stream. No corresponding argument
is used.
If the syntax of a conversion specication is invalid, the behavior is undened. If there aren't
enough function arguments provided to supply addresses for all the conversion specications in the
template strings that perform assignments, or if the arguments are not of the correct types, the
behavior is also undened. On the other hand, extra arguments are simply ignored.
20.2.11 Numeric Input Conversions
This section describes the scanf conversions for reading numeric values.
The ` d' conversion matches an optionally signed integer in decimal radix.
The ` i' conversion matches an optionally signed integer in any of the formats that the C
language denes for specifying an integer constant.
For example, any of the strings `10', `0xa', or `012' could be read in as integers under the ` i'
conversion. Each of these species a number with decimal value 10.
The ` o', ` u', and ` x' conversions match unsigned integers in octal, decimal, and hexadecimal
radices, respectively.
The ` X' conversion is identical to the ` x' conversion. They both permit either uppercase or
lowercase letters to be used as digits.
Unlike the C language scanf, Octave ignores the `h', `l', and `L' modiers.
20.2.12 String Input Conversions
This section describes the scanf input conversions for reading string and character values: ` s'
and ` c'.
The ` c' conversion is the simplest: it matches a xed number of characters, always. The
maximum eld with says how many characters to read if you don't specify the maximum, the
130 Octave
default is 1. This conversion does not skip over initial whitespace characters. It reads precisely the
next n characters, and fails if it cannot get that many.
The ` s' conversion matches a string of non-whitespace characters. It skips and discards initial
whitespace, but stops when it encounters more whitespace after having read something.
For example, reading the input:
hello, world
with the conversion ` 10c' produces " hello, wo", but reading the same input with the conversion
` 10s' produces "hello,".
The function feof le allows you to nd out if an end-of- le condition has been encountered
for a given le. Note that it will only return 1 if the end of the le has already been encountered,
not if the next read operation will result in an end-of- le condition.
Similarly, the function ferror le allows you to nd out if an error condition has been en-
countered for a given le. Note that it will only return 1 if an error has already been encountered,
not if the next operation will result in an error condition.
The function kbhit may be usd to read a single keystroke from the keyboard. For example,
x = kbhit
will set x to the next character typed at the keyboard, without requiring a carriage return to be
typed.
Finally, it is often useful to know exactly which les have been opened, and whether they are
open for reading, writing, or both. The command freport prints this information for all open les.
For example,
132 Octave
octave:13 freport
0 r stdin
1 w stdout
2 w stderr
3 r myfile
Chapter 21: Special Matrices 133
21 Special Matrices
Octave provides a number of functions for creating special matrix forms. In nearly all cases, it
is best to use the built-in functions for this purpose than to try to use other tricks to achieve the
same e ect.
instead of just
eye a
The rand function also takes some additional arguments that allow you to control its behavior.
For example, the function call
rand "normal"
causes the sequence of numbers to be normally distributed. You may also use an argument of
"uniform" to select a uniform distribution. To nd out what the current distribution is, use an
argument of "dist".
Normally, rand obtains the seed from the system clock, so that the sequence of random numbers
is not the same each time you run Octave. If you really do need for to reproduce a sequence of
numbers exactly, you can set the seed to a specic value. For example, the function call
rand "seed", 13
sets the seed to the number 13. To see what the current seed is, use the argument "seed".
If it is invoked without arguments, rand returns a single element of a random sequence.
The rand function uses Fortran code from RANLIB, a library of fortran routines for random
number generation, compiled by Barry W. Brown and James Lovato of the Department of Biomath-
ematics at The University of Texas, M.D. Anderson Cancer Center, Houston, TX 77030.
To create a diagonal matrix with vector v on diagonal k, use the function diag v, k . The
second argument is optional. If it is positive, the vector is placed on the k-th super-diagonal. If
it is negative, it is placed on the -k-th sub-diagonal. The default value of k is 0, and the vector is
placed on the main diagonal. For example,
octave:13 diag 1, 2, 3, 1
ans =
0 1 0 0
0 0 2 0
0 0 0 3
0 0 0 0
The functions linspace and logspace make it very easy to create vectors with evenly or
logarithmically spaced elements. For example,
linspace base, limit, n
creates a vector with n n greater than 2 linearly spaced elements between base and limit. The
base and limit are always included in the range. If base is greater than limit, the elements are
stored in decreasing order. If the number of points is not specied, a value of 100 is used.
The function logspace is similar to linspace except that the values are logarithmically spaced.
If limit is equal to , the points are between 10base and , not 10base and 10 , in order to be
compatible with the corresponding Matlab function.
Chapter 21: Special Matrices 135
22 Matrix Manipulation
There are a number of functions available for checking to see if the elements of a matrix meet
some condition, and for rearranging the elements of a matrix. For example, Octave can easily tell
you if all the elements of a matrix are nite, or are less than some speci ed value. Octave can also
rotate the elements, extract the upper- or lower-triangular parts, or sort the columns of a matrix.
1 1 0 0
To see if any of the elements of a matrix are nonzero, you can use a statement like
any any a
For a matrix argument, any returns a row vector of ones and zeros with each element indicating
whether any of the elements of the corresponding column of the matrix are nonzero.
The function all behaves like the function any, except that it returns true only if all the elements
of a vector, or all the elements in a column of a matrix, are nonzero.
Since the comparison operators see Section 3.11 Comparison Ops , page 34 return matrices
of ones and zeros, it is easy to test a matrix for many things, not just whether the elements are
nonzero. For example,
octave:13 all all rand 5 0.9
ans = 0
tests a random 5 by 5 matrix to see if all of it's elements are less than 0.9.
Note that in conditional contexts like the test clause of if and while statements Octave treats
the test as if you had typed all all condition .
The functions isinf, finite, and isnan return 1 if their arguments are in nite, nite, or not
a number, respectively, and return 0 otherwise. For matrix values, they all work on an element by
element basis. For example, evaluating the expression
isinf 1, 2 Inf, 4
produces the matrix
138 Octave
ans =
0 0
1 0
The function find returns a vector of indices of nonzero elements of a matrix. To obtain a single
index for each matrix element, Octave pretends that the columns of a matrix form one long vector
like Fortran arrays are stored. For example,
octave:13 find eye 2
ans =
1
4
If two outputs are requested, find returns the row and column indices of nonzero elements of a
matrix. For example,
octave:13 i, j = find eye 2
i =
1
2
j =
1
2
If three outputs are requested, find also returns the nonzero values in a vector.
2 1
4 3
octave:13 flipud 1, 2 3, 4
ans =
3 4
1 2
The function rot90 a, n rotates a matrix counterclockwise in 90-degree increments. The
second argument is optional, and speci es how many 90-degree rotations are to be applied the
default value is 1. Negative values of n rotate the matrix in a clockwise direction. For example,
Chapter 22: Matrix Manipulation 139
3 1
4 2
rotates the given matrix clockwise by 90 degrees. The following are all equivalent statements:
rot90 1, 2 3, 4 , -1
rot90 1, 2 3, 4 , 3
rot90 1, 2 3, 4 , 7
The function reshape a, m, n returns a matrix with m rows and n columns whose elements
are taken from the matrix a. To decide how to order the elements, Octave pretends that the
elements of a matrix are stored in column-major order like Fortran arrays are stored .
For example,
octave:13 reshape 1, 2, 3, 4 , 2, 2
ans =
1 3
2 4
but it is somewhat less cryptic to use reshape instead of the colon operator. Note that the total
number of elements in the original matrix must match the total number of elements in the new
matrix.
The function `sort' can be used to arrange the elements of a vector in increasing order. For
matrices, sort orders the elements in each column.
For example,
octave:13 sort rand 4
ans =
The sort function may also be used to produce a matrix containing the original row indices of
the elements in the sorted matrix. For example,
s =
i =
2 4 2 3
4 1 3 4
1 2 4 1
3 3 1 2
These values may be used to recover the original matrix from the sorted version. For example,
The sort function does not allow sort keys to be specied, so it can't be used to order the rows
of a matrix according to the values of the elements in various columns1 in a single call. Using the
second output, however, it is possible to sort all rows based on the values in a given column. Here's
an example that sorts the rows of a matrix based on the values in the third column.
octave:13 a = rand 4
a =
The functions triu a, k and tril a, k extract the upper or lower triangular part of the
matrix a, and set all other elements to zero. The second argument is optional, and species how
many diagonals above or below the main diagonal should also be set to zero.
The default value of k is zero, so that triu and tril normally include the main diagonal as
part of the result matrix.
If the value of k is negative, additional elements above for tril or below for triu the main
diagonal are also selected.
The absolute value of k must not be greater than the number of sub- or super-diagonals.
For example,
1
For example, to rst sort based on the values in column 1, and then, for any values that are
repeated in column 1, sort based on the values found in column 2, etc.
Chapter 22: Matrix Manipulation 141
23 String Functions
Octave currently has a limited ability to work with strings.
The function strcmp s1, s2 compares two strings, returning 1 if they are the same, and 0
otherwise.
Note: For compatibility with Matlab, Octave's strcmp function returns 1 if the strings are
equal, and 0 otherwise. This is just the opposite of the corresponding C library function.
The functions int2str and num2str convert a numeric argument to a string. These functions
are not very exible, but are provided for compatibility with Matlab. For better control over the
results, use sprintf see Section 20.2.2 Formatted Output , page 122.
The function setstr can be used to convert a vector to a string. Each element of the vector is
converted to the corresponding ASCII character. For example,
setstr 97, 98, 99
The function undo_string_escapes string converts special characters in strings back to their
escaped forms. For example, the expression
bell = "a"
assigns the value of the alert character control-g, ASCII code 7 to the string variable bell. If
this string is printed, the system will ring the terminal bell if it is possible. This is normally the
desired outcome. However, sometimes it is useful to be able to print the original representation of
the string, with the special characters replaced by their escape sequences. For example,
octave:13 undo_string_escapes bell
ans = a
replaces the unprintable alert character with its printable representation. See Section 3.1.2 String
Constants , page 22, for a description of string escapes.
144 Octave
Chapter 24: System Utilities 145
24 System Utilities
This chapter describes the functions that are available to allow you to get information about
what is happening outside of Octave, while it is still running, and use this information in your
program. For example, you can get information about environment variables, the current time,
and even start other programs from the Octave prompt.
1993 8 20 4 56 1
The function clock is more accurate on systems that have the gettimeofday function.
To get the date as a character string in the form DD-MMM-YY, use the command date. For
example,
octave:13 date
ans = 20-Aug-93
Octave also has functions for computing time intervals and CPU time used. The functions tic
and toc can be used to set and check a wall-clock timer. For example,
tic
# many computations later...
elapsed_time = toc
will set the variable elapsed_time to the number of seconds since the most recent call to the
function tic.
The function etime provides another way to get elapsed wall-clock time by returning the dier-
ence in seconds between two time values returned from clock. For example:
t0 = clock
# many computations later...
elapsed_time = etime clock , t0
will set the variable elapsed_time to the number of seconds since the variable t0 was set.
The function cputime allows you to obtain information about the amount of CPU time your
Octave session is using. For example,
total, user, system = cputime
returns the CPU time used by your Octave session. The rst output is the total time spent executing
your process and is equal to the sum of second and third outputs, which are the number of CPU
146 Octave
seconds spent executing in user mode and the number of CPU seconds spent executing in system
mode, respectively.
Finally, Octave's function is_leap_year returns 1 if the given year is a leap year and 0 otherwise.
If no arguments are provided, is_leap_year will use the current year. For example,
octave:13 is_leap_year 2000
ans = 1
Contrary to what many people who post misinformation to Usenet apparently believe, Octave
knows that the year 2000 will be a leap year.
The rst argument, `-i', tells bash to behave as an interactive shell, and the redirection of the
standard output stream prevents any output produced by bash from being sent back to Octave,
where it would be bu ered until Octave displays another prompt.
The system function can return two values. The rst is any output from the command that
was written to the standard output stream, and the second is the output status of the command.
For example,
output, status = system "echo foo exit 2"
will set the variable output to the string `foo', and the variable status to the integer `2'.
The name shell_cmd exists for compatibility with earlier versions of Octave.
You can nd the values of environment variables using the function getenv. For example,
getenv "PATH"
You can change the current working directory using the cd command. Tilde expansion is
performed on the path. For example,
cd ~octave
Changes the current working directory to `~octave'. If the directory does not exist, an error
message is printed and the working directory is not changed.
The name chdir is an alias for cd.
The command pwd prints the current working directory.
The functions dir and ls list directory contents. For example,
octave:13 ls -l
total 12
-rw-r--r-- 1 jwe users 4488 Aug 19 04:02 foo.m
-rw-r--r-- 1 jwe users 1315 Aug 17 23:14 bar.m
The dir and ls commands are implemented by calling your system's directory listing command,
so the available options may vary from system to system.
The function isieee returns 1 if your computer claims to conform to the IEEE standard for
oating point calculations.
The function version returns Octave's version number as a string. This is also the value of the
built-in variable OCTAVE_VERSION. See Chapter 6 Built-in Variables, page 61.
diary on
tells Octave to start recording your session in a le called `diary' in your current working directory.
To give Octave the name of the le write to, use the a command like
diary my-diary.txt
Then Octave will write all of your commands to the le `my-diary.txt'.
To stop recording your session, use the command
diary off
26 Help
Octave's help command can be used to print brief usage-style messages, or to display information
directly from an on-line version of the printed manual, using the GNU Info browser. If invoked
without any arguments, help prints a list of all the available operators, functions, and built-in
variables. If the rst argument is -i, the help command searches the index of the on-line version
of this manual for the given topics.
For example, the command
help help
prints a short message describing the help command, and
help -i help
starts the GNU Info browser at this node in the on-line version of the manual.
See Appendix D Using Info , page 183, for complete details about how to use the GNU Info
browser to read the on-line version of the manual.
152 Octave
Chapter 27: Programming Utilities 153
27 Programming Utilities
In this case, two values are printed: one for the expression that was evaluated, and one for the
value returned from eval. Just as with any other expression, you can turn printing o by ending
the expression in a semicolon. For example,
octave:13 a
error: `a' undefined
octave:14 eval "a = 13"
ans = 13
octave:15 a
a = 13
The function feval name, ... can be used to evaluate the function named name. Any
arguments after the rst are passed on to the named function. For example,
octave:12 feval "acos", -1
ans = 3.1416
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.
size a Return the number rows and columns of a. If there is only one output argument, the
result is returned in a 2 element row vector. If there are two output arguments, the
number of rows is assigned to the rst, and the number of columns to the second. For
example,
octave:13 size 1, 2 3, 4 5, 6
ans =
3 2
nc = 2
is_global a
Return 1 if a is globally visible. Otherwise, return 0.
is_matrix a
Return 1 if a is a matrix. Otherwise, return 0.
is_vector a
Return 1 if a is a vector. Otherwise, return 0.
is_scalar a
Return 1 if a is a scalar. Otherwise, return 0.
is_square x
If x is a square matrix, then return the dimension of x. Otherwise, return 0.
is_symmetric x, tol
If x is symmetric within the tolerance speci ed by tol, then return the dimension of x.
Otherwise, return 0. If tol is omitted, use a tolerance equal to the machine precision.
isstr a Return 1 if a is a string. Otherwise, return 0.
isempty a
Return 1 if a is an empty matrix either the number of rows, or the number of columns,
or both are zero . Otherwise, return 0.
clear pattern ...
Delete the names matching the given patterns from the symbol table. The pattern may
contain the following special characters:
? Match any single character.
* Match zero or more characters.
156 Octave
list Match the list of characters specied by list. If the rst character is ! or ^,
match all characters except those specied by list. For example, the pattern
` a-zA-Z' will match all lower and upper case alphabetic characters.
For example, the command
clear foo b*r
clears the name foo and all names that begin with the letter b and end with the letter
r.
If clear is called without any arguments, all user-dened variables local and global
are cleared from the symbol table. If clear is called with at least one argument,
only the visible names matching the arguments are cleared. For example, suppose you
have dened a function foo, and then hidden it by performing the assignment foo = 2.
Executing the command `clear foo' once will clear the variable denition and restore
the denition of foo as a function. Executing `clear foo' a second time will clear the
function denition.
This command may not be used within a function body.
who options pattern ...
List currently dened symbols matching the given patterns. The following are valid
options. They may be shortened to one character but may not be combined.
-all List all currently dened symbols.
-builtins
List built-in variables and functions. This includes all currently com-
piled function les, but does not include all function les that are in the
LOADPATH.
-functions
List user-dened functions.
-long Print a long listing including the type and dimensions of any symbols. The
symbols in the rst column of output indicate whether it is possible to
redene the symbol, and whether it is possible for it to be cleared.
-variables
List user-dened variables.
Valid patterns are the same as described for the clear command above. If no patterns
are supplied, all symbols from the given category are listed. By default, only user
dened functions and variables visible in the local scope are displayed.
The command whos is equivalent to who -long.
exist name
Return 1 if the name exists as a variable, and 2 if the name after appending `.m' is a
function le in the path. Otherwise, return 0.
Chapter 27: Programming Utilities 157
error msg
Print the message msg, prexed by the string `error: ', and set Octave's internal
error state such that control will return to the top level without evaluating any more
commands. This is useful for aborting from functions.
If msg does not end with a new line character, Octave will print a traceback of all the
function calls leading to the error. For example,
function f g end
function g h end
function h nargin == 1 || error "nargin != 1" end
f
error: nargin != 1
error: evaluating index expression near line 1, column 30
error: evaluating binary operator `||' near line 1, column 27
error: called from `h'
error: called from `g'
error: called from `f'
produces a list of messages that can help you to quickly locate the exact location of
the error.
If msg ends in a new line character, Octave will only print msg and will not display
any traceback messages as it returns control to the top level. For example, modifying
the error message in the previous example to end in a new line causes Octave to only
print a single message:
function h nargin == 1 || error "nargin != 1n" end
f
error: nargin != 1
warning msg
Print the message msg prexed by the string `warning: '.
usage msg
Print the message msg, prexed by the string `usage: ', and set Octave's internal
error state such that control will return to the top level without evaluating any more
commands. This is useful for aborting from functions.
After usage is evaluated, Octave will print a traceback of all the function calls leading
to the usage message.
perror name, num
Print the error message for function name corresponding to the error number num.
This function is intended to be used to print useful error messages for those functions
that return numeric error codes.
menu title, opt1, . . .
Print a title string followed by a series of options. Each option will be printed along
with a number. The return value is the number of the option selected by the user. This
function is useful for interactive programs. There is no limit to the number of options
158 Octave
that may be passed in, but it may be confusing to present more than will t easily on
one screen.
document symbol text
Set the documentation string for symbol to text.
file_in_path path, le
Return the absolute name name of le if it can be found in path. The value of path
should be a colon-separated list of directories in the format described for the built-in
variable LOADPATH.
If the le cannot be found in the path, an empty matrix is returned. For example,
octave:13 file_in_path LOADPATH, "nargchk.m"
ans = usr local lib octave 1.1.0 m general nargchk.m
28 Amusements
Octave cannot promise that you will actually win the lotto, but it can pick your numbers for
you. The function texas_lotto will select six numbers between 1 and 50.
The function list_primes n uses a brute-force algorithm to compute the rst n primes.
Other amusing functions include casesen, flops, sombrero, exit, and quit.
160 Octave
Appendix A: Installing Octave 161
GNU make, gcc, and libg++, gnuplot, bison, ex, and Texinfo are all available from many anony-
mous ftp archives, including ftp.che.utexas.edu, ftp.uu.net, prep.ai.mit.edu, and wuarchive.wustl.edu.
If you don't have a Fortran compiler, or if your Fortran compiler doesn't work like the tradi-
tional Unix f77, you will need to have the Fortran to C translator f2c. You can get f2c from
any number of anonymous ftp archives. The most recent version of f2c is always available from
research.att.com.
On an otherwise idle SPARCstation II, it will take somewhere between 60 and 90 minutes to
compile everything, depending on whether you are compiling the Fortran libraries with f2c or
using the Fortran compiler directly. You will need about 50 megabytes of disk storage to work
with considerably less if you don't compile with debugging symbols. To do that, use the
command
make CFLAGS=-O CXXFLAGS=-O LDFLAGS=
instead of just `make'.
If you encounter errors while compiling Octave, rst check the list of known problems below
to see if there is a workaround or solution for your problem. If not, see Appendix B Trouble,
page 167, for information about how to report bugs.
Once you have successfully compiled Octave, run `make install'.
This will install a copy of octave, its libraries, and its documentation in the destination direc-
tory. As distributed, Octave is installed in the following directories:
`prex bin'
Octave and other binaries that people will want to run directly.
`prex lib'
Libraries like libcruft.a and liboctave.a.
`prex includeoctave'
Include les distributed with Octave.
`prex manman1'
Unix-style man pages describing Octave.
`prex info'
Info les describing Octave.
`prex liboctaveversionm'
Function les distributed with Octave. This includes the Octave version, so that
multiple versions of Octave may be installed at the same time.
`prex liboctaveversionexechost type '
Executables to be run by Octave rather than the user.
`prex liboctaveversionocthost type '
Object les that will be dynamically loaded.
Appendix A: Installing Octave 163
With g++ 2.6.3 and possibly other 2.6.x versions on some Intel x86 systems, compiling
`Array-d.cc' fails with the messages like
as: tmpcc005254.s:4057: Local symbol LBB103 never defined.
as: tmpcc005254.s:4057: Local symbol LBE103 never defined.
A possible workaround for this is to compile without -g.
If Octave crashes immediately with a oating point exception, it is likely that it is failing to
initialize the IEEE oating point values for innity and NaN.
If your system actually does support IEEE arithmetic, you should be able to x this problem
by modifying the function octave_ieee_init in the le `sysdep.cc' to correctly initialize
Octave's internal innity and NaN variables.
If your system does not support IEEE arithmetic but Octave's congure script incorrectly
determined that it does, you can work around the problem by editing the le `config.h' to
not dene HAVE_ISINF, HAVE_FINITE, and HAVE_ISNAN.
In any case, please report this as a bug since it might be possible to modify Octave's congu-
ration script to automatically determine the proper thing to do.
where version stands for the current version number of the interpreter, and host type is the
type of computer on which Octave is installed for example, `i486-unknown-gnu'.
If these directories don't exist, the script `doinstall.sh' will create them for you.
If this is possible for you to install Octave in `usrlocal', or if you would prefer to install it
in a di erent directory, you can specify the name of the top level directory as an argument to
the doinstall.sh script. For example:
sh .doinstall.sh someotherdirectory
Octave will then be installed in subdirectories of the directory `someotherdirectory'
A.2.2 Creating a Binary Distribution
Here is how to build a binary distribution for others.
Build Octave in the same directory as the source. This is required since the `binary-dist'
targets in the Make les will not work if you compile outside the source tree.
Use `CFLAGS=-O CXXFLAGS=-O LDFLAGS=' as arguments for Make because most people who get
the binary distributions are probably not going to be interested in debugging Octave.
Type `make binary-dist'. This will build everything and then pack it up for distribution.
Appendix B: Known Causes of Trouble with Octave 167
You can buy a little bit of command line space by setting the environment variable TMPDIR to be
"." before starting Octave, or you can increase the maximum command line length in gnuplot
by changing the following limits in the le plot.h in the gnuplot distribution and recompiling
gnuplot.
#define MAX_LINE_LEN 32768 * originally 1024 *
#define MAX_TOKENS 8192 * originally 400 *
Of course, this doesn't really x the problem, but it does make it much less likely that you
will run into trouble unless you are putting a very large number of lines on a given plot.
String handling could use some work.
A list of ideas for future enhancements is distributed with Octave. See the le `PROJECTS' in
the top level directory in the source distribution.
If you are not sure whether you have found a bug, here are some guidelines:
If Octave gets a fatal signal, for any input whatever, that is a bug. Reliable interpreters never
crash.
If Octave produces incorrect results, for any input whatever, that is a bug.
Some output may appear to be incorrect when it is in fact due to a program whose behavior
is undened, which happened by chance to give the desired results on another system. For
example, the range operator may produce di erent results because of di erences in the way
oating point arithmetic is handled on various systems.
If Octave produces an error message for valid input, that is a bug.
Appendix B: Known Causes of Trouble with Octave 169
If Octave does not produce an error message for invalid input, that is a bug. However, you
should note that your idea of invalid input" might be my idea of an extension" or support
for traditional practice".
If you are an experienced user of programs like Octave, your suggestions for improvement are
welcome in any case.
If you have Octave working at all, the easiest way to prepare a complete bug report is to use
the Octave function bug_report. When you execute this function, Octave will prompt you for a
subject and then invoke the editor on a le that already contains all the conguration information.
When you exit the editor, Octave will mail the bug report for you.
If for some reason you cannot use Octave's bug_report function, send bug reports for Octave
to:
[email protected]
Do not send bug reports to `help-octave' . Most users of Octave do not want to receive bug
reports. Those that do have asked to be on `bug-octave'.
As a last resort, send bug reports on paper to:
Octave Bugs co John W. Eaton
Department of Chemical Engineering
The University of Texas at Austin
Austin, Texas 78712
The fundamental principle of reporting bugs usefully is this: . If you are not
report all the facts
Try to make your bug report self-contained. If we have to ask you for more information, it is
best if you include all the previous information in your response, as well as the information that
was missing.
To enable someone to investigate the bug, you should include all these things:
The version of Octave. You can get this by noting the version number that is printed when
Octave starts, or running it with the `-v' option.
A complete input le that will reproduce the bug.
A single statement may not be enough of an example|the bug might depend on other details
that are missing from the single statement where the error nally occurs.
The command arguments you gave Octave to execute that example and observe the bug. To
guarantee you won't omit something important, list all the options.
If we were to try to guess the arguments, we would probably guess wrong and then we would
not encounter the bug.
The type of machine you are using, and the operating system name and version number.
The command-line arguments you gave to the configure command when you installed the
interpreter.
A complete list of any modi cations you have made to the interpreter source.
Be precise about these changes|show a context di for them.
Details of any other deviations from the standard procedure for installing Octave.
A description of what behavior you observe that you believe is incorrect. For example, "The
interpreter gets a fatal signal," or, "The output produced at line 208 is incorrect."
Of course, if the bug is that the interpreter gets a fatal signal, then one can't miss it. But if
the bug is incorrect output, we might not notice unless it is glaringly wrong.
Even if the problem you experience is a fatal signal, you should still say so explicitly. Suppose
something strange is going on, such as, your copy of the interpreter is out of synch, or you
have encountered a bug in the C library on your system. Your copy might crash and the copy
here would not. If you said to expect a crash, then when the interpreter here fails to crash, we
would know that the bug was not happening. If you don't say to expect a crash, then we would
not know whether the bug was happening. We would not be able to draw any conclusion from
our observations.
Often the observed symptom is incorrect output when your program is run. Unfortunately,
this is not enough information unless the program is short and simple. It is very helpful if you
can include an explanation of the expected output, and why the actual output is incorrect.
If you wish to suggest changes to the Octave source, send them as context di s. If you even
discuss something in the Octave source, refer to it by context, not by line number, because the
line numbers in the development sources probalby won't match those in your sources.
Here are some things that are not necessary:
Appendix B: Known Causes of Trouble with Octave 171
If you would like to write bug xes or improvements for Octave, that is very helpful. When you
send your changes, please follow these guidelines to avoid causing extra work for us in studying the
patches.
If you don't follow these guidelines, your information might still be useful, but using it will take
extra work. Maintaining Octave is a lot of work in the best of circumstances, and we can't keep
up unless you do your best to help.
Send an explanation with your changes of what problem they x or what improvement they
bring about. For a bug x, just include a copy of the bug report, and explain why the change
xes the bug.
Always include a proper bug report for the problem you think you have xed. We need to
convince ourselves that the change is right before installing it. Even if it is right, we might
have trouble judging it if we don't have a way to reproduce the problem.
Include all the comments that are appropriate to help people reading the source in the future
understand why this change was needed.
Don't mix together changes made for dierent reasons. Send them individually.
If you make two changes for separate reasons, then we might not want to install them both.
We might want to install just one.
Use `diff -c' to make your dis. Dis without context are hard for us to install reliably. More
than that, they make it hard for us to study the dis to decide whether we want to install
them. Unidi format is better than contextless dis, but not as easy to read as `-c' format.
If you have GNU di, use `diff -cp', which shows the name of the function that each change
occurs in.
172 Octave
If you need help installing, using or changing Octave, the mailing list
[email protected]
exists for the discussion of Octave matters related to using, installing, and porting Octave. If
you would like to join the discussion, please send a short note to
[email protected]
^^^^^^^
Please do not send requests to be added or removed from the the mailing list, or other admin-
istrative trivia to the list itself.
Appendix C: Command Line Editing 173
Often during an interactive session you type in a long line of text, only to notice that the rst
word on the line is misspelled. The Readline library gives you a set of commands for manipulating
the text as you type it in, allowing you to just x your typo, and not forcing you to retype the
majority of the line. Using these editing commands, you move the cursor to the place that needs
correction, and delete or insert the text of the corrections. Then, when you are satised with the
line, you simply press RETURN. You do not have to be at the end of the line to press RETURN the
entire line is accepted regardless of the location of the cursor within the line.
In order to enter characters into the line, simply type them. The typed character appears where
the cursor was, and then the cursor moves one space to the right. If you mistype a character, you
can use DEL to back up, and delete the mistyped character.
Sometimes you may miss typing a character that you wanted to type, and not notice your error
until you have typed several other characters. In that case, you can type C-B to move the cursor
to the left, and then correct your mistake. Afterwards, you can move the cursor to the right with
C-F.
174 Octave
When you add text in the middle of a line, you will notice that characters to the right of the
cursor get `pushed over' to make room for the text that you have inserted. Likewise, when you
delete text behind the cursor, characters to the right of the cursor get `pulled back' to ll in the
blank space created by the removal of the text. A list of the basic bare essentials for editing the
text of an input line follows.
C-B Move back one character.
C-F Move forward one character.
DEL Delete the character to the left of the cursor.
C-D Delete the character underneath the cursor.
Printing characters
Insert itself into the line at the cursor.
C-_ Undo the last thing that you did. You can undo all the way back to an empty line.
M-DEL Kill from the cursor to the start of the previous word, or if between words, to the start
of the previous word.
C-W Kill from the cursor to the previous whitespace. This is dierent than M-DEL because
the word boundaries dier.
And, here is how to yank the text back into the line. Yanking is
C-Y Yank the most recently killed text back into the buer at the cursor.
M-Y Rotate the kill-ring, and yank the new top. You can only do this if the prior command
is C-Y or M-Y.
When you use a kill command, the text is saved in a kill-ring. Any number of consecutive kills
save all of the killed text together, so that when you yank it back, you get it in one clean sweep.
The kill ring is not line speci c the text that you killed on a previously typed line is available to
be yanked back later, when you are typing another line.
Variable Settings
You can change the state of a few variables in Readline. You do this by using the set
command within the init le. Here is how you would specify that you wish to use Vi
line editing commands:
set editing-mode vi
Right now, there are only a few variables which can be set so few in fact, that we just
iterate them here:
editing-mode
The editing-mode variable controls which editing mode you are using.
By default, GNU Readline starts up in Emacs editing mode, where the
keystrokes are most similar to Emacs. This variable can either be set to
emacs or vi.
horizontal-scroll-mode
This variable can either be set to On or Off. Setting it to On means that
the text of the lines that you edit will scroll horizontally on a single screen
line when they are larger than the width of the screen, instead of wrapping
onto a new screen line. By default, this variable is set to Off.
mark-modified-lines
This variable when set to On, says to display an asterisk `*' at the starts
of history lines which have been modied. This variable is o by default.
prefer-visible-bell
If this variable is set to On it means to use a visible bell if one is available,
rather than simply ringing the terminal bell. By default, the value is Off.
Key Bindings
The syntax for controlling keybindings in the `~.inputrc' le is simple. First you
have to know the name of the command that you want to change. The following pages
contain tables of the command name, the default keybinding, and a short description
of what the command does.
Once you know the name of the command, simply place the name of the key you wish
to bind the command to, a colon, and then the name of the command on a line in the
`~.inputrc' le. The name of the key can be expressed in di erent ways, depending
on which is most comfortable for you.
keyname: function-name or macro
keyname is the name of a key spelled out in English. For example:
Control-u: universal-argument
Meta-Rubout: backward-kill-word
Control-o: " &output"
Appendix C: Command Line Editing 177
previous-history C-P
Move `up' through the history list.
next-history C-N
Move `down' through the history list.
beginning-of-history M-
Move to the rst line in the history.
end-of-history M-
Move to the end of the input history, i.e., the line you are entering!
reverse-search-history C-R
Search backward starting at the current line and moving `up' through the history as
necessary. This is an incremental search.
forward-search-history C-S
Search forward starting at the current line and moving `down' through the the history
as necessary.
C.8.3 Commands For Changing Text
delete-char C-D
Delete the character under the cursor. If the cursor is at the beginning of the line,
and there are no characters in the line, and the last character typed was not C-D, then
return EOF.
backward-delete-char Rubout
Delete the character behind the cursor. A numeric arg says to kill the characters instead
of deleting them.
quoted-insert C-Q, C-V
Add the next character that you type to the line verbatim. This is how to insert things
like C-Q for example.
tab-insert M-TAB
Insert a tab character.
self-insert a, b, A, 1, !, ...
Insert yourself.
transpose-chars C-T
Drag the character before point forward over the character at point. Point moves
forward as well. If point is at the end of the line, then transpose the two characters
before point. Negative args don't work.
transpose-words M-T
Drag the word behind the cursor past the word in front of the cursor moving the cursor
over that word as well.
Appendix C: Command Line Editing 179
upcase-word M-U
Uppercase the current or following word. With a negative argument, do the previous
word, but do not move point.
downcase-word M-L
Lowercase the current or following word. With a negative argument, do the previous
word, but do not move point.
capitalize-word M-C
Uppercase the current or following word. With a negative argument, do the previous
word, but do not move point.
C.8.4 Killing And Yanking
kill-line C-K
Kill the text from the current cursor position to the end of the line.
backward-kill-line
Kill backward to the beginning of the line. This is normally unbound.
kill-word M-D
Kill from the cursor to the end of the current word, or if between words, to the end of
the next word.
backward-kill-word M-DEL
Kill the word behind the cursor.
unix-line-discard C-U
Do what C-U used to do in Unix line input. We save the killed text on the kill-ring,
though.
unix-word-rubout C-W
Do what C-W used to do in Unix line input. The killed text is saved on the kill-ring.
This is di erent than backward-kill-word because the word boundaries di er.
yank C-Y
Yank the top of the kill ring into the bu er at point.
yank-pop M-Y
Rotate the kill-ring, and yank the new top. You can only do this if the prior command
is yank or yank-pop.
C.8.5 Specifying Numeric Arguments
digit-argument M-0, M-1, ... M--
Add this digit to the argument already accumulating, or start a new argument. M--
starts a negative argument.
180 Octave
universal-argument
Do what C-U does in emacs. By default, this is not bound.
C.8.6 Letting Readline Type For You
complete TAB
Attempt to do completion on the text before point. This is implementation dened.
Generally, if you are typing a le name argument, you can do le name completion if
you are typing a command, you can do command completion, if you are typing in a
symbol to GDB, you can do symbol name completion, if you are typing in a variable
to Bash, you can do variable name completion...
possible-completions M-?
List the possible completions of the text before point.
C.8.7 Some Miscellaneous Commands
re-read-init-file C-X C-R
Read in the contents of your `~.inputrc' le, and incorporate any bindings found
there.
abort C-G
Ding! Stops things.
do-uppercase-version M-A, M-B, ...
Run the command that is bound to your uppercase brother.
prefix-meta ESC
Make the next character that you type be metaed. This is for people without a meta
key. Typing ESC F is equivalent to typing M-F.
undo C-_
Incremental undo, separately remembered for each line.
revert-line M-R
Undo all changes made to this line. This is like typing the `undo' command enough
times to get back to the beginning.
While the Readline library does not have a full set of Vi editing functions, it does contain enough
to allow simple editing of the line.
In order to switch interactively between Emacs and Vi editing modes, use the command M-C-J
toggle-editing-mode .
Appendix C: Command Line Editing 181
When you enter a line in Vi mode, you are already placed in `insertion' mode, as if you had
typed an `i'. Pressing ESC switches you into `edit' mode, where you can edit the text of the line
with the standard Vi movement keys, move to previous history lines with `k', and following lines
with `j', and so forth.
182 Octave
Appendix D: Using Info 183
Many people nd that reading screens of text page by page is made easier when one is able to
indicate particular pieces of text with some kind of pointing device. Since this is the case, GNU
Info both the Emacs and standalone versions have several commands which allow you to move the
cursor about the screen. The notation used in this manual to describe keystrokes is identical to the
notation used within the Emacs manual, and the GNU Readline manual. See section Character
Conventions" in the GNU Emacs Manual, if you are unfamiliar with the notation.
The following table lists the basic cursor movement commands in Info. Each entry consists of the
key sequence you should type to execute the cursor movement, the M-x1 command name displayed
in parentheses , and a short description of what the command does. All of the cursor motion
commands can take an numeric argument see Section D.8 Other Info Commands, page 193 , to
nd out how to supply them. With a numeric argument, the motion commands are simply executed
that many times for example, a numeric argument of 4 given to next-line causes the cursor to
move down 4 lines. With a negative numeric argument, the motion is reversed an argument of -4
given to the next-line command would cause the cursor to move up 4 lines.
C-n next-line
Moves the cursor down to the next line.
C-p prev-line
Move the cursor up to the previous line.
C-a beginning-of-line
Move the cursor to the start of the current line.
C-e end-of-line
Moves the cursor to the end of the current line.
C-f forward-char
Move the cursor forward a character.
C-b backward-char
Move the cursor backward a character.
1
M-x is also a command it invokes execute-extended-command. See section Executing an
extended command" in the GNU Emacs Manual, for more detailed information.
184 Octave
M-f forward-word
Moves the cursor forward a word.
M-b backward-word
Moves the cursor backward a word.
M- beginning-of-node
b Moves the cursor to the start of the current node.
M- end-of-node
Moves the cursor to the end of the current node.
M-r move-to-window-line
Moves the cursor to a specic line of the window. Without a numeric argument, M-r
moves the cursor to the start of the line in the center of the window. With a numeric
argument of n, M-r moves the cursor to the start of the nth line in the window.
Sometimes you are looking at a screenful of text, and only part of the current paragraph you
are reading is visible on the screen. The commands detailed in this section are used to shift which
part of the current node is visible on the screen.
SPC scroll-forward
C-v Shift the text in this window up. That is, show more of the node which is currently
below the bottom of the window. With a numeric argument, show that many more
lines at the bottom of the window a numeric argument of 4 would shift all of the text
in the window up 4 lines discarding the top 4 lines, and show you four new lines at
the bottom of the window. Without a numeric argument, SPC takes the bottom two
lines of the window and places them at the top of the window, redisplaying almost a
completely new screenful of lines.
DEL scroll-backward
M-v Shift the text in this window down. The inverse of scroll-forward.
The scroll-forward and scroll-backward commands can also move forward and backward
through the node structure of the le. If you press SPC while viewing the end of a node, or DEL while
viewing the beginning of a node, what happens is controlled by the variable scroll-behaviour.
See Section D.9 Info Variables , page 195, for more information.
C-l redraw-display
Redraw the display from scratch, or shift the line containing the cursor to a specied
location. With no numeric argument, `C-l' clears the screen, and then redraws its entire
contents. Given a numeric argument of n, the line containing the cursor is shifted so
that it is on the nth line of the window.
Appendix D: Using Info 185
C-x w toggle-wrap
Toggles the state of line wrapping in the current window. Normally, lines which are
longer than the screen width wrap, i.e., they are continued on the next line. Lines which
wrap have a `' appearing in the rightmost column of the screen. You can cause such
lines to be terminated at the rightmost column by changing the state of line wrapping
in the window with C-x w. When a line which needs more space than one screen width
to display is displayed, a `$' appears in the rightmost column of the screen, and the
remainder of the line is invisible.
D.3 Selecting a New Node
This section details the numerous Info commands which select a new node to view in the current
window.
The most basic node commands are `n', `p', `u', and `l'.
When you are viewing a node, the top line of the node contains some Info pointers which describe
where the next, previous, and up nodes are. Info uses this line to move about the node structure
of the le when you use the following commands:
n next-node
Selects the `Next' node.
p prev-node
Selects the `Prev' node.
u up-node
Selects the `Up' node.
You can easily select a node that you have already viewed in this window by using the `l'
command this name stands for "last", and actually moves through the list of already visited
nodes for this window. `l' with a negative numeric argument moves forward through the history
of nodes for this window, so you can quickly step between two adjacent in viewing history nodes.
l history-node
Selects the most recently selected node in this window.
Two additional commands make it easy to select the most commonly selected nodes they are
`t' and `d'.
t top-node
Selects the node `Top' in the current info le.
d dir-node
Selects the directory node i.e., the node `dir'.
Here are some other commands which immediately result in the selection of a dierent node in
the current window:
186 Octave
first-node
Selects the rst node which appears in this le. This node is most often `Top', but it
doesn't have to be.
last-node
Selects the last node which appears in this le.
global-next-node
Moves forward or down through node structure. If the node that you are currently
viewing has a `Next' pointer, that node is selected. Otherwise, if this node has a menu,
the rst menu item is selected. If there is no `Next' and no menu, the same process is
tried with the `Up' node of this node.
global-prev-node
Moves backward or up through node structure. If the node that you are currently
viewing has a `Prev' pointer, that node is selected. Otherwise, if the node has an `Up'
pointer, that node is selected, and if it has a menu, the last item in the menu is selected.
You can get the same behavior as global-next-node and global-prev-node while simply
scrolling through the le with SPC and DEL See Section D.9 Info Variables, page 195, for more
information.
g goto-node
Reads the name of a node and selects it. No completion is done while reading the node
name, since the desired node may reside in a separate le. The node must be typed
exactly as it appears in the info le. A le name may be included as with any node
specication, for example
gemacsBuffers
nds the node `Buffers' in the info le `emacs'.
C-x k kill-node
Kills a node. The node name is prompted for in the echo area, with a default of the
current node. Killing a node means that Info tries hard to forget about it, removing it
from the list of history nodes kept for the window where that node is found. Another
node is selected in the window which contained the killed node.
C-x C-f view-file
Reads the name of a le and selects the entire le. The command
C-x C-f lename
is equivalent to typing
glename *
C-x b select-visited-node
Selects a node which has been previously visited in a visible window. This is similar
to `C-x C-b' followed by `m', but no window is created.
GNU Info allows you to search for a sequence of characters throughout an entire info le, search
through the indices of an info le, or nd areas within an info le which discuss a particular topic.
s search
Reads a string in the echo area and searches for it.
C-s isearch-forward
Interactively searches forward through the info le for a string as you type it.
C-r isearch-backward
Interactively searches backward through the info le for a string as you type it.
i index-search
Looks up a string in the indices for this info le, and selects a node where the found
index entry points to.
, next-index-match
Moves to the node containing the next matching index item from the last `i' command.
The most basic searching command is `s' search. The `s' command prompts you for a string
in the echo area, and then searches the remainder of the info le for an occurrence of that string. If
the string is found, the node containing it is selected, and the cursor is left positioned at the start
of the found string. Subsequent `s' commands show you the default search string within `' and
`' pressing RET instead of typing a new string will use the default search string.
Incremental searching is similar to basic searching, but the string is looked up while you are
typing it, instead of waiting until the entire search string has been speci ed.
We have already discussed the `Next', `Prev', and `Up' pointers which appear at the top of a
node. In addition to these pointers, a node may contain other pointers which refer you to a dierent
node, perhaps in another info le. Such pointers are called cross references, or xrefs for short.
D.5.1 Parts of an Xref
Cross references have two major parts: the rst part is called the label it is the name that you
can use to refer to the cross reference, and the second is the target it is the full name of the node
that the cross reference points to.
188 Octave
The target is separated from the label by a colon `:' rst the label appears, and then the target.
For example, in the sample menu cross reference below, the single colon separates the label from
the target.
* Foo Label: Foo Target. More information about Foo.
Note the `.' which ends the name of the target. The `.' is not part of the target it serves only
to let Info know where the target name ends.
A shorthand way of specifying references allows two adjacent colons to stand for a target name
which is the same as the label name:
* Foo Commands:: Commands pertaining to Foo.
In the above example, the name of the target is the same as the name of the label, in this case
Foo Commands.
You will normally see two types of cross references while viewing nodes: menu references, and
note references. Menu references appear within a node's menu they begin with a `*' at the
beginning of a line, and continue with a label, a target, and a comment which describes what the
contents of the node pointed to contains.
Note references appear within the body of the node text they begin with *Note, and continue
with a label and a target.
Like `Next', `Prev' and `Up' pointers, cross references can point to any valid node. They are
used to refer you to a place where more detailed information can be found on a particular subject.
Here is a cross reference which points to a node within the Texinfo documentation: See section
Writing an Xref" in the Texinfo Manual, for more information on creating your own texinfo cross
references.
D.5.2 Selecting Xrefs
The following table lists the Info commands which operate on menu items.
1 menu-digit
2 ... 9 Within an Info window, pressing a single digit, such as `1' , selects that menu item,
and places its node in the current window. For convenience, there is one exception
pressing `0' selects the last item in the node's menu.
0 last-menu-item
Select the last item in the current node's menu.
m menu-item
Reads the name of a menu item in the echo area and selects its node. Completion is
available while reading the menu label.
M-x find-menu
Moves the cursor to the start of this node's menu.
Appendix D: Using Info 189
This table lists the Info commands which operate on note cross references.
f xref-item
r Reads the name of a note cross reference in the echo area and selects its node. Com-
pletion is available while reading the cross reference label.
Finally, the next few commands operate on menu or note references alike:
TAB move-to-next-xref
Moves the cursor to the start of the next nearest menu item or note reference in this
node. You can then use RET select-reference-this-line to select the menu or
note reference.
M-TAB move-to-prev-xref
Moves the cursor the start of the nearest previous menu item or note reference in this
node.
RET select-reference-this-line
Selects the menu item or note reference appearing on this line.
A window is a place to show the text of a node. Windows have a view area where the text of
the node is displayed, and an associated mode line, which brie y describes the node being viewed.
GNU Info supports multiple windows appearing in a single screen each window is separated
from the next by its modeline. At any time, there is only one active window, that is, the window in
which the cursor appears. There are commands available for creating windows, changing the size
of windows, selecting which window is active, and for deleting windows.
A mode line is a line of inverse video which appears at the bottom of an info window. It
describes the contents of the window just above it this information includes the name of the le
and node appearing in that window, the number of screen lines it takes to display the node, and
the percentage of text that is above the top of the window. It can also tell you if the indirect tags
table for this info le needs to be updated, and whether or not the info le was compressed when
stored on disk.
Here is a sample mode line for a window containing an uncompressed le named `dir', showing
the node `Top'.
-----Info: dirTop, 40 lines --Top---------------------------------------
^^ ^ ^^^ ^^
fileNode #lines where
190 Octave
When a node comes from a le which is compressed on disk, this is indicated in the mode line
with two small `z''s. In addition, if the info le containing the node has been split into subles, the
name of the suble containing the node appears in the modeline as well:
--zz-Info: emacsTop, 291 lines --Top-- Subfile: emacs-1.Z---------------
When Info makes a node internally, such that there is no corresponding info le on disk, the
name of the node is surrounded by asterisks `*' . The name itself tells you what the contents of
the window are the sample mode line below shows an internally constructed node showing possible
completions:
-----Info: *Completions*, 7 lines --All-----------------------------------
C-x ^ grow-window
Grows or shrinks the current window. Given a numeric argument, grows the current
window that many lines with a negative numeric argument, the window is shrunk
instead.
C-x t tile-windows
Divides the available screen space among all of the visible windows. Each window is
given an equal portion of the screen in which to display its contents. The variable
automatic-tiling can cause tile-windows to be called when a window is created or
deleted. See Section D.9 automatic-tiling , page 195.
D.6.3 The Echo Area
The echo area is a one line window which appears at the bottom of the screen. It is used to
display informative or error messages, and to read lines of input from you when that is necessary.
Almost all of the commands available in the echo area are identical to their Emacs counterparts,
so please refer to that documentation for greater depth of discussion on the concepts of editing a
line of text. The following table brie y lists the commands that are available while input is being
read in the echo area:
C-f echo-area-forward
Moves forward a character.
C-b echo-area-backward
Moves backward a character.
C-a echo-area-beg-of-line
Moves to the start of the input line.
C-e echo-area-end-of-line
Moves to the end of the input line.
M-f echo-area-forward-word
Moves forward a word.
M-b echo-area-backward-word
Moves backward a word.
C-d echo-area-delete
Deletes the character under the cursor.
DEL echo-area-rubout
Deletes the character behind the cursor.
C-g echo-area-abort
Cancels or quits the current operation. If completion is being read, `C-g' discards the
text of the input line which does not match any completion. If the input line is empty,
`C-g' aborts the calling function.
192 Octave
RET echo-area-newline
Accepts or forces completion of the current input line.
C-q echo-area-quoted-insert
Inserts the next character verbatim. This is how you can insert control characters into
a search string, for example.
printing character echo-area-insert
Inserts the character.
M-TAB echo-area-tab-insert
Inserts a TAB character.
C-t echo-area-transpose-chars
Transposes the characters at the cursor.
The next group of commands deal with killing, and yanking text. For an in depth discussion of
killing and yanking, see section Killing and Deleting" in the GNU Emacs Manual
M-d echo-area-kill-word
Kills the word following the cursor.
M-DEL echo-area-backward-kill-word
Kills the word preceding the cursor.
C-k echo-area-kill-line
Kills the text from the cursor to the end of the line.
C-x DEL echo-area-backward-kill-line
Kills the text from the cursor to the beginning of the line.
C-y echo-area-yank
Yanks back the contents of the last kill.
M-y echo-area-yank-pop
Yanks back a previous kill, removing the last yanked text rst.
Sometimes when reading input in the echo area, the command that needed input will only
accept one of a list of several choices. The choices represent the possible completions, and you
must respond with one of them. Since there are a limited number of responses you can make,
Info allows you to abbreviate what you type, only typing as much of the response as is necessary
to uniquely identify it. In addition, you can request Info to ll in as much of the response as is
possible this is called completion.
The following commands are available when completing in the echo area:
TAB echo-area-complete
SPC Inserts as much of a completion as is possible.
Appendix D: Using Info 193
? echo-area-possible-completions
Displays a window containing a list of the possible completions of what you have typed
so far. For example, if the available choices are:
bar
foliate
food
forget
and you have typed an `f', followed by `?', the possible completions would contain:
foliate
food
forget
i.e., all of the choices which begin with `f'. Pressing SPC or TAB would result in `fo'
appearing in the echo area, since all of the choices which begin with `f' continue with
`o'. Now, typing `l' followed by `TAB' results in `foliate' appearing in the echo area,
since that is the only choice which begins with `fol'.
ESC C-v echo-area-scroll-completions-window
Scrolls the completions window, if that is visible, or the "other" window if not.
M-x where-is
Reads the name of an Info command in the echo area, and then displays a key sequence
which can be typed in order to invoke that command.
C-h get-help-window
? Creates or moves into the window displaying *Help*, and places a node containing a
quick reference card into it. This window displays the most concise information about
GNU Info available.
h get-info-help-node
Tries hard to visit the node infoHelp. The info le `info.texi' distributed with
GNU Info contains this node. Of course, the le must rst be processed with makeinfo,
and then placed into the location of your info directory.
Here are the commands for creating a numeric argument:
C-u universal-argument
Starts or multiplies by 4 the current numeric argument. `C-u' is a good way to give a
small numeric argument to cursor movement or scrolling commands `C-u C-v' scrolls
the screen 4 lines, while `C-u C-u C-n' moves the cursor down 16 lines.
M-1 add-digit-to-numeric-arg
M-2 . . . M-9
Adds the digit value of the invoking key to the current numeric argument. Once Info is
reading a numeric argument, you may just type the digits of the argument, without the
Meta prex. For example, you might give `C-l' a numeric argument of 32 by typing:
C-u 3 2 C-l
or
M-3 2 C-l
`C-g' is used to abort the reading of a multi-character key sequence, to cancel lengthy operations
such as multi-le searches and to cancel reading input in the echo area.
C-g abort-key
Cancels current operation.
The `q' command of Info simply quits running Info.
q quit Exits GNU Info.
If the operating system tells GNU Info that the screen is 60 lines tall, and it is actually only 40
lines tall, here is a way to tell Info that the operating system is correct.
M-x set-screen-height
Reads a height value in the echo area and sets the height of the displayed screen to
that value.
Appendix D: Using Info 195
Finally, Info provides a convenient way to display footnotes which might be associated with the
current node that you are viewing:
ESC C-f show-footnotes
Shows the footnotes if any associated with the current node in another window.
You can have Info automatically display the footnotes associated with a node when
the node is selected by setting the variable automatic-footnotes. See Section D.9
automatic-footnotes , page 195.
GNU Info contains several variables whose values are looked at by various Info commands. You
can change the values of these variables, and thus change the behavior of Info to more closely match
your environment and info le reading manner.
M-x set-variable
Reads the name of a variable, and the value for it, in the echo area and then sets the
variable to that value. Completion is available when reading the variable name often,
completion is available when reading the value to give to the variable, but that depends
on the variable itself. If a variable does not supply multiple choices to complete over,
it expects a numeric value.
M-x describe-variable
Reads the name of a variable in the echo area and then displays a brief description of
what the variable aects.
Here is a list of the variables that you can set in Info.
automatic-footnotes
When set to On, footnotes appear and disappear automatically. This variable is On
by default. When a node is selected, a window containing the footnotes which appear
in that node is created, and the footnotes are displayed within the new window. The
window that Info creates to contain the footnotes is called `*Footnotes*'. If a node
is selected which contains no footnotes, and a `*Footnotes*' window is on the screen,
the `*Footnotes*' window is deleted. Footnote windows created in this fashion are not
automatically tiled so that they can use as little of the display as is possible.
automatic-tiling
When set to On, creating or deleting a window resizes other windows. This variable
is Off by default. Normally, typing `C-x 2' divides the current window into two equal
parts. When automatic-tiling is set to On, all of the windows are resized automat-
ically, keeping an equal number of lines visible in each window. There are exceptions
to the automatic tiling speci cally, the windows `*Completions*' and `*Footnotes*'
are not resized through automatic tiling they remain their original size.
196 Octave
visible-bell
When set to On, GNU Info attempts to ash the screen instead of ringing the bell. This
variable is Off by default. Of course, Info can only ash the screen if the terminal allows
it in the case that the terminal does not allow it, the setting of this variable has no
eect. However, you can make Info perform quietly by setting the errors-ring-bell
variable to Off.
errors-ring-bell
When set to On, errors cause the bell to ring. The default setting of this variable is On.
gc-compressed-files
When set to On, Info garbage collects les which had to be uncompressed. The default
value of this variable is Off. Whenever a node is visited in Info, the info le containing
that node is read into core, and Info reads information about the tags and nodes
contained in that le. Once the tags information is read by Info, it is never forgotten.
However, the actual text of the nodes does not need to remain in core unless a particular
info window needs it. For non-compressed les, the text of the nodes does not remain
in core when it is no longer in use. But de-compressing a le can be a time consuming
operation, and so Info tries hard not to do it twice. gc-compressed-files tells Info it
is okay to garbage collect the text of the nodes of a le which was compressed on disk.
show-index-match
When set to On, the portion of the matched search string is highlighted in the message
which explains where the matched search string was found. The default value of this
variable is On. When Info displays the location where an index match was found, see
Section D.4 next-index-match, page 187, the portion of the string that you had
typed is highlighted by displaying it in the inverse case from its surrounding characters.
scroll-behaviour
Controls what happens when forward scrolling is requested at the end of a node, or
when backward scrolling is requested at the beginning of a node. The default value for
this variable is Continuous. There are three possible values for this variable:
Continuous
Tries to get the rst item in this node's menu, or failing that, the `Next'
node, or failing that, the `Next' of the `Up'. This behavior is identical to
using the `' global-next-node and `' global-prev-node commands.
Next Only Only tries to get the `Next' node.
Page Only Simply gives up, changing nothing. If scroll-behaviour is Page Only, no
scrolling command can change the node that is being viewed.
scroll-step
The number of lines to scroll when the cursor moves out of the window. Scrolling
happens automatically if the cursor has moved out of the visible portion of the node
Appendix D: Using Info 197
text when it is time to display. Usually the scrolling is done so as to put the cursor
on the center line of the current window. However, if the variable scroll-step has
a nonzero value, Info attempts to scroll the node text by that many lines if that is
enough to bring the cursor back into the window, that is what is done. The default
value of this variable is 0, thus placing the cursor and the text it is attached to in the
center of the window. Setting this variable to 1 causes a kind of "smooth scrolling"
which some people prefer.
ISO-Latin
When set to On, Info accepts and displays ISO Latin characters. By default, Info
assumes an ASCII character set. ISO-Latin tells Info that it is running in an envi-
ronment where the European standard character set is in use, and allows you to input
such characters to Info, as well as display them.
198 Octave
Concept Index 199
Concept Index
# arguments in function call . . . . . . . . . . . . . . . . . . . . . . . . . 29
`#' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 arithmetic operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
`#!'. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 assignment expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
assignment operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
`' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 B
body of a loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
- boolean expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
--debug ........................................... 19 boolean operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
--echo-commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 break statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
. D
... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53, 54 DAE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
data structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
A decrement operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 dening functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
addition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 Dierential Equations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
amusements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158 dis, submitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
and operator.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 division.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
answers, incorrect. . . . . . . . . . . . . . . . . . . . . . . . . . . . 168, 170 documenting Octave programs . . . . . . . . . . . . . . . . . . . . . 15
200 Octave
erroneous messages ............................... 168 input conversions, for scanf ...................... 128
erroneous results
............................. 168, 170 installation trouble ............................... 167
error messages, incorrect .......................... 168 installing Octave .................................. 161
escape sequence notation ........................... 22 introduction ....................................... 11
executable scripts
.................................. 15 invalid input ...................................... 168
exiting octave 11
J
......................................
exponentiation..................................... 33
expression, range.................................. 25 job hunting ........................................ 25
expressions........................................ 21
expressions, assignment ............................ 37 K
expressions, boolean ............................... 35 keywords .......................................... 32
expressions, comparison ............................ 34 known causes of trouble ........................... 167
expressions, logical 35
.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
L
F less than operator .................................. 34
factorial function
.................................. 31 logical expressions ................................. 35
fatal signal
....................................... 168 logical operators ................................... 35
ag character printf ........................... 123 loop ............................................... 43
ag character scanf ............................. 128 lottery numbers .................................. 159
ying high and fast ................................ 25 LP ................................................ 91
for statement ..................................... 44 lvalue .............................................. 37
Fordyce, A. P..................................... 153
function le
........................................ 55 M
functions, user-dened ............................. 49 matching failure, in scanf ........................ 127
matrices 23
G
.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
H N
help, where to nd ................................ 172 negation ........................................... 33
Concept Index 201
statements .........................................
20
41
Octave command options .......................... 19 strings........................................ 22, 141
ODE .............................................. 89 structures ......................................... 27
operator precedence ................................ 39 submitting dis ................................... 171
operators, arithmetic ............................... 33 submitting patches ............................... 171
operators, assignment .............................. 37 subtraction ........................................ 33
operators, boolean ................................. 35 suggestions ....................................... 169
operators, decrement 39
T
...............................
undened behavior
33
168
patches, submitting ............................... 171 ...............................
R W
range expressions .................................. 25 warranty ............................................ 2
relational operators ................................ 34 while statement ................................... 43
reporting bugs ............................... 168, 169 wrong answers ............................... 168, 170
202 Octave
Variable Index 203
Variable Index
A P
ans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 page screen output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
automatic replot ............................ 64, 108 PAGER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
pi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
PS1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
67
63
EDITOR ............................................ 62
PS2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
empty list elements ok . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
PWD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
eps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
G R
realmax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
gnuplot binary ................................... 65 realmin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
I
resize on range error . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
return last computed value ...................... 67
I, i, J, j . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
ignore function time stamp ...................... 65 S
IMAGEPATH . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 save precision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67, 119
N stdout ............................................ 62
NaN, nan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
nargout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
T
treat neg dim as zero ............................ 68
O W
OCTAVE VERSION ................................... 63 warn assign as truth value . . . . . . . . . . . . . . . . . . . . . . . 68
ok to lose imaginary part . . . . . . . . . . . . . . . . . . . . . . . . 65 warn comma in global decl . . . . . . . . . . . . . . . . . . . . . . . . 69
output max field width . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 warn divide by zero .............................. 69
output precision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 whitespace in literal matrix . . . . . . . . . . . . . . . . . . . . 64
204 Octave
Function Index 205
Function Index
- B
-ascii ...................................... 119, 120 balance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
-binary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 x y . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
bar ,
-float-binary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 beta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
-force ........................................... 120 betai a, b, x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
-mat-binary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120, 121 bug report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168, 169
-save-builtins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
. C
c2d , a b, t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
.octaverc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
casesen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
cd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
ceil x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
x .......................................
cumprod 73 fftconv , a b, N . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
cumsum x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 fftfilt b, x, N . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
fgets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
E fseek . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
fsolve . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
edit history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
fsolve options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
eig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
ftell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
erf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
fwrite le, data, precision . . . . . . . . . . . . . . . . . . . . 130
erfc z . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
erfinv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
error msg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157 G
etime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 gamma z . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
eval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153 gammai a, x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
exp x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 givens . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
F gray2ind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
grid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
fclose ........................................... 122
gsplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
feof.............................................. 131
ferror . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
feval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
131
153 H
fflush . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 hadamard k ..................................... 135
fft a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 hankel , c r .................................... 135
fft2 a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Function Index 207
N
isieee . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
isinf ............................................ 137
isnan 137
............................................
nargchk nargin min, nargin max, n . . . . . . . . . . . . 158
isstr a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
newtroot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
norm a, p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
K npsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
kbhit ............................................ 131 npsol options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
keyboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 null a, tol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
kron a, b . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 num2str . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
208 Octave
O residue , b a, tol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
ocean n ........................................ 116 rgb2ind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 rot90 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
P
pause
perror
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
name, num . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
S
save . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
pinv X, tol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
saveimage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
plot args . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
scanf template .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
polar theta, rho . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
schur . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
poly a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
sec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
polyderiv c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
sech . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
polyinteg c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
semilogx args . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
polyreduce c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
semilogy args . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
polyval c, x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
polyvalm c, x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
setstr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
printf template, ... . . . . . . . . . . . . . . . . . . . . . . . . . . 122
shell cmd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
prod x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
show . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
purge tmp files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
sign x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
pwd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
sin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Q sinc x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
sinh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
qpsol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 size a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
qpsol options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 skewness x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
qr a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 sombrero n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
quad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 sort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
quad options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 sprintf template, ... . . . . . . . . . . . . . . . . . . . . . . . . . 122
quit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11, 159 sqrt x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
qzhess a, b . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 sqrtm a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
qzval a, b . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81 sscanf string, template .. . . . . . . . . . . . . . . . . . . . . . . 127
stairs x, y . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
R std a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
rand. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 strcmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
rank a, tol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77 sum x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
real x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 sumsq x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
rem x, y . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 svd a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
replot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 syl a, b, c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
reshape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139 system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Function Index 209
T va start . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
tan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 vander c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
tanh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73 version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
texas lotto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 vr val . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
tic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
title string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
toc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
W
warning msg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
toeplitz c, r . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
which name ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
trace a . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
who options pattern ... . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
tril . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
whos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
triu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
type name ... . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
tzero a, b, c, d, bal . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 X
xlabel string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
U
undo string escapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
union . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Y
ylabel string . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
usage msg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
V Z
va arg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 zeros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
210 Octave
Operator Index 211
Operator Index
! =
! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 = . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
!= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 == . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
&
& . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
&& . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22, 33
"
*
" .................................................. 22
* .................................................. 33
** . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
|
| .................................................. 35
,
|| . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
, . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
-
~
~ .................................................. 35
- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
~= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
.................................................. 39
.
+
+ .................................................. 33
.' . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
.* . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
.** . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
.- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
.................................................. 34
.+ ................................................. 33
= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
.^
^
................................................. 33
. ................................................. 33
^ .................................................. 33
.................................................. 33
.................................................. 33
:
: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
.................................................. 34
= . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
212 Octave
Readline Index 213
Readline Index
A K
abort C-G . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180 kill-line C-K ................................. 179
accept-line Newline, Return . . . . . . . . . . . . . . . . . . 177 kill-word M-D ................................. 179
B M
backward-char C-B . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 mark-modified-lines ............................ 176
backward-delete-char Rubout . . . . . . . . . . . . . . . . . 178
backward-kill-line ..........................
C prefer-visible-bell ............................
prefix-meta ESC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
176
180
capitalize-word M-C .......................... 179
previous-history C-P ......................... 178
clear-screen C-L . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
complete TAB .................................. 180
Q
D quoted-insert C-Q, C-V ....................... 178
E
editing-mode .................................... 176 S
end-of-history M- . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 self-insert a, b, A, 1, !, ... . . . . . . . . . . . . . . . . 178
end-of-line C-E . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
F T
tab-insert M-TAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
forward-char C-F . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 transpose-chars C-T .......................... 178
forward-search-history C-S .................. 178 transpose-words M-T .......................... 179
forward-word M-F . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
H U
undo C- ....................................... 180
horizontal-scroll-mode . . . . . . . . . . . . . . . . . . . . . . . . . 176 universal-argument .......................... 180
Info Index
............................
194
184
0, in Info windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
C-w, in Info windows ............................ 185
..........................
191
190
1 ::: 9, in Info windows . . . . . . . . . . . . . . . . . . . . . . . . . 188
C-x 1, in Info windows .......................... 190
..........................
190
187
abort-key . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 C-x C-b, in Info windows . . . . . . . . . . . . . . . . . . . . . . . . 186
add-digit-to-numeric-arg . . . . . . . . . . . . . . . . . . . . . . . 194
C-x C-f, in Info windows . . . . . . . . . . . . . . . . . . . . . . . . 186
automatic-footnotes ............................ 195 C-x DEL, in the Info echo area . . . . . . . . . . . . . . . . . . 192
automatic-tiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 C-x k, in Info windows .......................... 186
..........................
190
191
b, in Info windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 C-y, in the Info echo area ...................... 192
backward-char . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 cancelling the current operation . . . . . . . . . . . . . . . 194
backward-word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 cancelling typeahead . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
beginning-of-line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 commands, describing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
beginning-of-node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184 cursor, moving .................................. 183
C
C-a, in Info windows ............................ 183
216 Octave
D F
d, in Info windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 f, in Info windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
DEL, in Info windows ............................ 184 find-menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
DEL, in the Info echo area . . . . . . . . . . . . . . . . . . . . . . 191 first-node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
delete-window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190 footnotes, displaying .......................... 195
describe-command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193 forward-char .................................... 183
describe-key .................................... 193 forward-word .................................... 184
describe-variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195 functions, describing .......................... 193
dir-node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
G
g, in Info windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
gc-compressed-files 196
E
............................
get-help-window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
echo area . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
get-info-help-node ............................. 194
global-next-node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
echo-area-abort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
global-prev-node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
echo-area-backward ............................. 191
goto-node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
echo-area-backward-kill-line . . . . . . . . . . . . . . . . . . 192
echo-area-backward-kill-word . . . . . . . . . . . . . . . . . . 192 grow-window ..................................... 191
echo-area-backward-word . .......................
echo-area-beg-of-line . . . . . . . . . . . . . . . . . . . . . . . . . .
191
191 H
echo-area-complete ............................. 193 h, in Info windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
echo-area-delete . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191 history-node .................................... 185
echo-area-end-of-line . . . . . . . . . . . . . . . . . . . . . . . . . . 191
echo-area-forward . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
echo-area-forward-word . . . . . . . . . . . . . . . . . . . . . . . . .
191
191
I
i, in Info windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
echo-area-insert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
index-search .................................... 187
echo-area-kill-line ............................ 192
INFO PRINT COMMAND, environment variable . . . . . . 193
echo-area-kill-word ............................ 192
isearch-backward . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
echo-area-newline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
isearch-forward . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
echo-area-possible-completions . . . . . . . . . . . . . . . . 193
ISO Latin characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
echo-area-quoted-insert . ....................... 192
ISO-Latin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
echo-area-rubout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
echo-area-scroll-completions-window . .........
echo-area-tab-insert . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
193
K
keep-one-window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
echo-area-transpose-chars ..................... 192
keys, describing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
echo-area-yank . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
kill-node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
echo-area-yank-pop ............................. 192
end-of-line
end-of-node
.....................................
.....................................
183
184 L
errors-ring-bell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196 l, in Info windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
ESC C-f, in Info windows . . . . . . . . . . . . . . . . . . . . . . . . 195 last-menu-item . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
ESC C-v, in Info windows . . . . . . . . . . . . . . . . . . . . . . . . 191 last-node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
ESC C-v, in the Info echo area . . . . . . . . . . . . . . . . . . 193 list-visited-nodes ............................. 186
Info Index 217
M quitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
S
M-d, in the Info echo area . . . . . . . . . . . . . . . . . . . . . . 192
M-DEL, in the Info echo area . . . . . . . . . . . . . . . . . . . . 192
M-f, in Info windows ............................ 184 s, in Info windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
M-f, in the Info echo area . . . . . . . . . . . . . . . . . . . . . . 191 screen, changing the height of . . . . . . . . . . . . . . . . . 195
M-r, in Info windows ............................ 184 scroll-backward . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
M-TAB, in Info windows . . . . . . . . . . . . . . . . . . . . . . . . . . 189 scroll-behaviour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
M-TAB, in the Info echo area . . . . . . . . . . . . . . . . . . . . 192 scroll-forward . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
M-v, in Info windows ............................ 184 scroll-other-window ............................ 191
M-y, in the Info echo area . . . . . . . . . . . . . . . . . . . . . . 192 scroll-step ..................................... 197
menu-digit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 scrolling through node structure . . . . . . . . . . . . . . . 184
menu-item . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188 scrolling, in Info windows ..................... 184
move-to-next-xref . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 search ........................................... 187
move-to-prev-xref . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189 searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
move-to-window-line ............................ 184 select-reference-this-line .................... 189
N select-visited-node ............................
set-screen-height . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
187
T
numeric arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
Q U
u, in Info windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
q, in Info windows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 universal-argument ............................. 194
quit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 up-node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
218 Octave
W X
where-is . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194 xref-item . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
i
Table of Contents
Preface ................................................. 1
GNU GENERAL PUBLIC LICENSE ................. 3
Preamble . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND
MODIFICATION . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Appendix: How to Apply These Terms to Your New Programs . . . . . . . . . 8
1 A Brief Introduction to Octave ................... 11
1.1 Running Octave . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.2 Simple Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Creating a Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Matrix Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Solving Linear Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Integrating Di erential Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Producing Graphical Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Editing What You Have Typed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Getting Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Help via Info . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.3 Executable Octave Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.4 Comments in Octave Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
1.5 Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2 Invoking Octave ................................... 19
2.1 Command Line Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.2 Startup Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3 Expressions ....................................... 21
3.1 Constant Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.1.1 Numeric Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
3.1.2 String Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.2 Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.2.1 Empty Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.3 Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.4 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.5 Index Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.6 Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
ii Octave
3.7 Calling Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
3.7.1 Call by Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
3.7.2 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.8 Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.9 Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
3.10 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.11 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.12 Boolean Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.12.1 Element-by-element Boolean Operators . . . . . . . . . . . . . . . . 35
3.12.2 Short-circuit Boolean Operators . . . . . . . . . . . . . . . . . . . . . . 36
3.13 Assignment Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
3.14 Increment Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.15 Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
4 Statements ........................................ 41
4.1 The if Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
4.2 The while Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
4.3 The for Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.4 The break Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
4.5 The continue Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.6 The unwind protect Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
5 Functions and Script Files ........................ 49
5.1 Dening Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
5.2 Multiple Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
5.3 Variable-length Argument Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
5.4 Variable-length Return Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.5 Returning From a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
5.6 Function Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
5.7 Script Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
5.8 Dynamically Linked Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
5.9 Organization of Functions Distributed with Octave . . . . . . . . . . . . . . 58
6 Built-in Variables ................................. 61
6.1 Predened Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
6.2 User Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
6.3 Other Built-in Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
6.4 Summary of Preference Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
iii
7 Arithmetic ........................................ 71
7.1 Utility Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
7.2 Complex Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
7.3 Trigonometry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
7.4 Sums and Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
7.5 Special Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
8 Linear Algebra .................................... 75
8.1 Basic Matrix Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
8.2 Matrix Factorizations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
8.3 Functions of a Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
9 Polynomial Manipulations ........................ 83
10 Nonlinear Equations ............................. 87
11 Dierential Equations ............................ 89
11.1 Ordinary Di erential Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
11.2 Di erential-Algebraic Equations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
12 Optimization ..................................... 91
12.1 Quadratic Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
12.2 Nonlinear Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
12.3 Linear Least Squares . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
13 Quadrature ...................................... 93
13.1 Functions of one Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
13.2 Orthogonal Collocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
14 Control Theory .................................. 95
15 Signal Processing ............................... 101
16 Sets ............................................. 103
17 Statistics ........................................ 105
iv Octave
18 Plotting ......................................... 107
18.1 Two-Dimensional Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
18.2 Three-Dimensional Plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
18.3 Miscellaneous Plotting Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
19 Image Processing ............................... 115
20 Input and Output .............................. 117
20.1 Basic Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
20.2 C-Style I O Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
20.2.1 Opening and Closing Files . . . . . . . . . . . . . . . . . . . . . . . . . . 121
20.2.2 Formatted Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
20.2.3 Output Conversion Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . 123
20.2.4 Table of Output Conversions . . . . . . . . . . . . . . . . . . . . . . . . 124
20.2.5 Integer Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
20.2.6 Floating-Point Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . 125
20.2.7 Other Output Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . 126
20.2.8 Formatted Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
20.2.9 Input Conversion Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
20.2.10 Table of Input Conversions . . . . . . . . . . . . . . . . . . . . . . . . . 128
20.2.11 Numeric Input Conversions . . . . . . . . . . . . . . . . . . . . . . . . . 129
20.2.12 String Input Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
20.2.13 Binary I O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
20.2.14 Other I O Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
21 Special Matrices ................................ 133
21.1 Special Utility Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
21.2 Famous Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
22 Matrix Manipulation ........................... 137
22.1 Finding Elements and Checking Conditions . . . . . . . . . . . . . . . . . . . 137
22.2 Rearranging Matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
23 String Functions ................................ 143
24 System Utilities . ................................ 145
24.1 Timing Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
24.2 Interacting with the OS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
24.3 System Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
24.4 Other Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
v
25 Command History Functions ................... 149
26 Help ............................................ 151
27 Programming Utilities . ......................... 153
27.1 Evaluating Strings as Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
27.2 Miscellaneous Utilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
28 Amusements .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Appendix A Installing Octave ..................... 161
A.1 Installation Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
A.2 Binary Distributions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
A.2.1 Installing Octave from a Binary Distribution . . . . . . . . . . 165
A.2.2 Creating a Binary Distribution . . . . . . . . . . . . . . . . . . . . . . . 166
Appendix B Known Causes of Trouble with Octave
167
.................................................