You are on page 1of 3

Octave Quick Reference Octave Version 3.0.0 Killing and Yanking shiftdim (arr, s) rotate the array dimensions.

C-k kill to the end of the line circshift (arr, s) rotate the array elements.
Starting Octave C-y yank the most recently killed text
octave start interactive Octave session M-d kill to the end of the current word Sparse Matrices
octave file run Octave on commands in file M-DEL kill the word behind the cursor sparse (...) create a sparse matrix.
octave --eval code Evaluate code using Octave M-y rotate the kill ring and yank the new top
speye (n) create sparse identity matrix.
octave --help describe command line options
sprand (n, m, d) sparse rand matrix of density d.
Command Completion and History spdiags (...) sparse generalization of diag.
Stopping Octave TAB complete a command or variable name nnz (s) No. nonzero elements in sparse matrix.
quit or exit exit Octave M-? list possible completions
INTERRUPT (e.g. C-c) terminate current command RET enter the current line
C-p move ‘up’ through the history list
Ranges
and return to top-level prompt
C-n move ‘down’ through the history list base : limit
M-< move to the first line in the history base : incr : limit
Getting Help M-> move to the last line in the history Specify a range of values beginning with base with no
help list all commands and built-in variables C-r search backward in the history list elements greater than limit. If it is omitted, the default
help command briefly describe command C-s search forward in the history list value of incr is 1. Negative increments are permitted.
doc use Info to browse Octave manual
history [-q] [N ] list N previous history lines, omitting
doc command search for command in Octave manual
history numbers if -q
Strings and Common Escape Sequences
lookfor str search for command based on str
A string constant consists of a sequence of characters enclosed
history -w [file] write history to file (~/.octave hist if
in either double-quote or single-quote marks. Strings in
Motion in Info no file argument)
double-quotes allow the use of the escape sequences below.
SPC or C-v scroll forward one screenful history -r [file] read history from file (~/.octave hist if
DEL or M-v scroll backward one screenful \\ a literal backslash
no file argument)
C-l redraw the display \" a literal double-quote character
edit history lines edit and then run previous commands
\’ a literal single-quote character
from the history list
\n newline, ASCII code 10
Node Selection in Info run history lines run previous commands from the history \t horizontal tab, ASCII code 9
n select the next node list
p select the previous node [beg ] [end ] Specify the first and last history
Index Expressions
u select the ‘up’ node commands to edit or run.
t select the ‘top’ node If beg is greater than end, reverse the list of commands var (idx) select elements of a vector
d select the directory node before editing. If end is omitted, select commands from var (idx1, idx2) select elements of a matrix
< select the first node in the current file beg to the end of the history list. If both arguments are scalar select row (column) corresponding to
> select the last node in the current file omitted, edit the previous item in the history list. scalar
vector select rows (columns) corresponding to the
g reads the name of a node and selects it
Shell Commands elements of vector
C-x k kills the current node
range select rows (columns) corresponding to the
cd dir change working directory to dir
elements of range
Searching in Info pwd print working directory
: select all rows (columns)
s search for a string ls [options] print directory listing
C-s search forward incrementally
C-r search backward incrementally
getenv (string) return value of named environment Global and Persistent Variables
variable
i search index & go to corresponding node global var1 ... Declare variables global.
system (cmd) execute arbitrary shell command string
, go to next match from last ‘i’ command global var1 = val Declare variable global. Set initial value.
persistent var1 Declare a variable as static to a function.
Matrices persistent var1 = Declare a variable as static to a function
Command-Line Cursor Motion Square brackets delimit literal matrices. Commas separate val and set its initial value.
C-b move back one character elements on the same row. Semicolons separate rows. Commas Global variables may be accessed inside the body of a function
C-f move forward one character may be replaced by spaces, and semicolons may be replaced by without having to be passed in the function parameter list
C-a move to the start of the line one or more newlines. Elements of a matrix may be arbitrary provided they are declared global when used.
C-e move to the end of the line expressions, assuming all the dimensions agree.
M-f move forward a word Selected Built-in Functions
M-b move backward a word
[ x, y, ... ] enter a row vector
[ x; y; ... ] enter a column vector EDITOR editor to use with edit history
C-l clear screen, reprinting current line at top
[ w, x; y, z ] enter a 2×2 matrix Inf, NaN IEEE infinity, NaN
NA Missing value
Inserting or Changing Text PAGER program to use to paginate output
M-TAB insert a tab character
Multi-dimensional Arrays
ans last result not explicitly assigned
DEL delete character to the left of the cursor Multi-dimensional arrays may be created with the cat or
eps machine precision
reshape commands from two-dimensional sub-matrices.
C-d delete character under the cursor pi π
C-v add the next character verbatim squeeze (arr) remove singleton dimensions of the array. √
C-t transpose characters at the point
1i −1
ndims (arr) number of dimensions in the array. realmax maximum representable value
M-t transpose words at the point permute (arr, p) permute the dimensions of an array. realmin minimum representable value
[] surround optional arguments ... show one or more arguments
ipermute (arr, p) array inverse permutation.
Copyright 1996, 1997, 2007 John W. Eaton Permissions on back
Assignment Expressions Paths and Packages Function Handles
var = expr assign expression to variable path display the current Octave function path. @func Define a function handle to func.
var (idx) = expr assign expression to indexed variable pathdef display the default path. @(var1, ...) expr Define an anonymous function handle.
var (idx) = [] delete the indexed elements. addpath (dir) add a directory to the path. str2func (str) Create a function handle from a string.
var {idx} = expr assign elements of a cell array. EXEC PATH manipulate the Octave executable path. functions (handle) Return information about a function
pkg list display installed packages. handle.
pkg load pack Load an installed package. func2str (handle) Return a string representation of a
Arithmetic and Increment Operators function handle.
x + y addition handle (arg1, ...) Evaluate a function handle.
x - y subtraction
Cells and Structures feval (func, arg1, Evaluate a function handle or string,
x * y matrix multiplication var.field = ... set a field of a structure. ...) passing remaining args to func
x .* y element by element multiplication var{idx} = ... set an element of a cell array. Anonymous function handles take a copy of the variables in
x / y right division, conceptually equivalent to cellfun (f, c) apply a function to elements of cell array. the current workspace.
(inverse (y’) * x’)’ fieldnames (s) returns the fields of a structure.
x ./ y element by element right division
Miscellaneous Functions
x \ y left division, conceptually equivalent to
Statements eval (str) evaluate str as a command
inverse (x) * y
for identifier = expr stmt-list endfor error (message) print message and return to top level
x .\ y element by element left division
Execute stmt-list once for each column of expr. The warning (message) print a warning message
x ^ y power operator
variable identifier is set to the value of the current column clear pattern clear variables matching pattern
x .^ y element by element power operator
during each iteration. exist (str) check existence of variable or function
- x negation
who, whos list current variables
+ x unary plus (a no-op)
while (condition) stmt-list endwhile whos var details of the variable var
x ’ complex conjugate transpose
x .’ transpose Execute stmt-list while condition is true.
++ x (-- x) increment (decrement), return new value
Basic Matrix Manipulations
x ++ (x --) increment (decrement), return old value break exit innermost loop rows (a) return number of rows of a
continue go to beginning of innermost loop columns (a) return number of columns of a
return return to calling function all (a) check if all elements of a nonzero
Comparison and Boolean Operators any (a) check if any elements of a nonzero
These operators work on an element-by-element basis. Both if (condition) if-body [else else-body] endif
arguments are always evaluated.
Execute if-body if condition is true, otherwise execute else- find (a) return indices of nonzero elements
x < y true if x is less than y body. sort (a) order elements in each column of a
x <= y true if x is less than or equal to y sum (a) sum elements in columns of a
if (condition) if-body [elseif (condition) elseif-body] endif
x == y true if x is equal to y prod (a) product of elements in columns of a
x >= y true if x is greater than or equal to y Execute if-body if condition is true, otherwise execute the
min (args) find minimum values
x > y true if x is greater than y elseif-body corresponding to the first elseif condition that
max (args) find maximum values
x != y true if x is not equal to y is true, otherwise execute else-body.
rem (x, y) find remainder of x/y
x & y true if both x and y are true Any number of elseif clauses may appear in an if
reshape (a, m, n) reformat a to be m by n
x | y true if at least one of x or y is true statement.
diag (v, k) create diagonal matrices
! bool true if bool is false
unwind protect body unwind protect cleanup cleanup end linspace (b, l, n) create vector of linearly-spaced elements
Short-circuit Boolean Operators Execute body. Execute cleanup no matter how control exits logspace (b, l, n) create vector of log-spaced elements
body. eye (n, m) create n by m identity matrix
Operators evaluate left-to-right. Operands are only evaluated if
try body catch cleanup end ones (n, m) create n by m matrix of ones
necessary, stopping once overall truth value can be determined.
Execute body. Execute cleanup if body fails. zeros (n, m) create n by m matrix of zeros
Operands are converted to scalars using the all function.
rand (n, m) create n by m matrix of random values
x && y true if both x and y are true
Strings
x || y true if at least one of x or y is true
strcmp (s, t) compare strings Linear Algebra
strcat (s, t, ...) concatenate strings chol (a) Cholesky factorization
Operator Precedence regexp (str, pat) strings matching regular expression det (a) compute the determinant of a matrix
Table of Octave operators, in order of increasing precedence. eig (a) eigenvalues and eigenvectors
regexprep (str, pat, rep) Match and replace sub-strings
; , statement separators expm (a) compute the exponential of a matrix
= assignment, groups left to right Defining Functions hess (a) compute Hessenberg decomposition
|| && logical “or” and “and” inverse (a) invert a square matrix
| & element-wise “or” and “and” function [ret-list] function-name [ (arg-list) ] norm (a, p) compute the p-norm of a matrix
< <= == >= > != relational operators function-body pinv (a) compute pseudoinverse of a
: colon
endfunction qr (a) compute the QR factorization of a matrix
+ - addition and subtraction
rank (a) matrix rank
* / \ .* ./ .\ multiplication and division ret-list may be a single identifier or a comma-separated list of sprank (a) structural matrix rank
’ .’ transpose identifiers delimited by square-brackets.
+ - ++ -- ! unary minus, increment, logical “not” schur (a) Schur decomposition of a matrix
arg-list is a comma-separated list of identifiers and may be svd (a) singular value decomposition
^ .^ exponentiation
empty. syl (a, b, c) solve the Sylvester equation
Equations, ODEs, DAEs, Quadrature disp (var) display value of var to screen Polynomials
*fsolve solve nonlinear algebraic equations compan (p) companion matrix
*lsode integrate nonlinear ODEs conv (a, b) convolution
*dassl integrate nonlinear DAEs deconv (a, b) deconvolve two vectors
*quad integrate nonlinear functions poly (a) create polynomial from a matrix
perror (nm, code) for functions that return numeric codes, polyderiv (p) derivative of polynomial
print error message for named function polyreduce (p) integral of polynomial
and given error code
polyval (p, x) value of polynomial at x
* See the on-line or printed manual for the complete list of polyvalm (p, x) value of polynomial at x
arguments for these functions. roots (p) polynomial roots
residue (a, b) partial fraction expansion of ratio a/b
Signal Processing
fft (a) Fast Fourier Transform using FFTW
ifft (a) inverse FFT using FFTW
Statistics
freqz (args) FIR filter frequency response corrcoef (x, y) correlation coefficient
cov (x, y) covariance
filter (a, b, x) filter by transfer function
mean (a) mean value
conv (a, b) convolve two vectors
median (a) median value
hamming (n) return Hamming window coefficients
std (a) standard deviation
hanning (n) return Hanning window coefficients var (a) variance

Image Processing Plotting Functions


colormap (map) set the current colormap plot (args) 2D plot with linear axes
gray2ind (i, n) convert gray scale to Octave image plot3 (args) 3D plot with linear axes
image (img, zoom) display an Octave image matrix line (args) 2D or 3D line
imagesc (img, zoom) display scaled matrix as image patch (args) 2D patch
imread (file) load an image file semilogx (args) 2D plot with logarithmic x-axis
imshow (img, map) display Octave image semilogy (args) 2D plot with logarithmic y-axis
imshow (i, n) display gray scale image
loglog (args) 2D plot with logarithmic axes
imshow (r, g, b) display RGB image
imwrite (img, file) write images in various file formats
bar (args) plot bar charts
ind2gray (img, map) convert Octave image to gray scale
stairs (x, y) plot stairsteps
stem (x, y) plot a stem graph
ind2rgb (img, map) convert indexed image to RGB
hist (y, x) plot histograms
rgb2ind (r, g, b) convert RGB to Octave image contour (x, y, z) contour plot
save a matrix to file title (string) set plot title
axis (limits) set axis ranges
C-style Input and Output xlabel (string) set x-axis label
fopen (name, mode) open file name ylabel (string) set y-axis label
fclose (file) close file zlabel (string) set z-axis label
printf (fmt, ...) formatted output to stdout text (x, y, str) add text to a plot
fprintf (file, fmt, ...) formatted output to file legend (string) set label in plot key
sprintf (fmt, ...) formatted output to string grid [on|off] set grid state
scanf (fmt) formatted input from stdin hold [on|off] set hold state
fscanf (file, fmt) formatted input from file ishold return 1 if hold is on, 0 otherwise
sscanf (str, fmt) formatted input from string mesh (x, y, z) plot 3D surface
fgets (file, len) read len characters from file meshgrid (x, y) create mesh coordinate matrices
fflush (file) flush pending output to file
ftell (file) return file pointer position
frewind (file) move file pointer to beginning
freport print a info for open files Edition 2.0 for Octave Version 3.0.0. Copyright 1996, 2007, John
W. Eaton (jwe@octave.org). The author assumes no responsibility
fread (file, size, prec) read binary data files
for any errors on this card.
fwrite (file, size, prec) write binary data files
feof (file) determine if pointer is at EOF This card may be freely distributed under the terms of the GNU
A file may be referenced either by name or by the number General Public License.
returned from fopen. Three files are preconnected when
TEX Macros for this card by Roland Pesch (pesch@cygnus.com),
Octave starts: stdin, stdout, and stderr.
originally for the GDB reference card

Other Input and Output functions Octave itself is free software; you are welcome to distribute copies
of it under the terms of the GNU General Public License. There is
save file var ... save variables in file
absolutely no warranty for Octave.
load file load variables from file

You might also like