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.
The simplest type of expression is the constant, which always has the same value. There are two types of constants: numeric constants and string constants.
A numeric constant may be a scalar, a vector, or a matrix, and it may contain complex values.
The simplest form of a numeric constant, a scalar, is a single number that can be an integer, a decimal fraction, a number in scientific (exponential) notation, or a complex number. Note that all numeric values are represented within Octave in doubleprecision floating point format (complex constants are stored as pairs of doubleprecision floating point values). Here are some examples of realvalued numeric constants, which all have the same value:
105 1.05e+2 1050e1
To specify complex constants, you can write an expression of the form
3 + 4i 3.0 + 4.0i 0.3e1 + 40e1i
all of which are equivalent. The letter `i' in the previous example stands for the pure imaginary constant, defined as
For Octave to recognize a value as the imaginary part of a complex constant, a space must not appear between the number and the `i'. If it does, Octave will print an error message, like this:
octave:13> 3 + 4 i parse error: 3 + 4 i ^
You may also use `j', `I', or `J' in place of the `i' above. All four forms are equivalent.
A string constant consists of a sequence of characters enclosed in either doublequote or singlequote marks. For example, both of the following expressions
"parrot" 'parrot'
represent the string whose contents are `parrot'. Strings in Octave can be of any length.
Since the singlequote mark is also used for the transpose operator (see section Arithmetic Operators) but doublequote marks have no other purpose in Octave, it is best to use doublequote marks to denote strings.
Some characters cannot be included literally in a string constant. You represent them instead with escape sequences, which are character sequences beginning with a backslash (`\').
One use of an escape sequence is to include a doublequote
(singlequote) character in a string constant that has been defined
using doublequote (singlequote) marks. Since a plain doublequote
would end the string, you must use `\"' to represent a single
doublequote character as a part of the string. The backslash character
itself is another character that cannot be included normally. You must
write `\\' to put one backslash in the string. Thus, the string
whose contents are the two characters `"\' must be written
"\"\\"
.
Another use of backslash is to represent unprintable characters such as newline. While there is nothing to stop you from writing most of these characters directly in a string constant, they may look ugly.
Here is a table of all the escape sequences used in Octave. They are the same as those used in the C programming langauge.
\\
\"
\'
\a
\b
\f
\n
\r
\t
\v
Strings may be concatenated using the notation for defining matrices. For example, the expression
[ "foo" , "bar" , "baz" ]
produces the string whose contents are `foobarbaz'. The next section explains more about how to create matrices.
It is easy to define a matrix of values in Octave. The size of the matrix is determined automatically, so it is not necessary to explicitly state the dimensions. The expression
a = [1, 2; 3, 4]
results in the matrix
Elements of a matrix may be arbitrary expressions, provided that the dimensions all make sense when combining the various pieces. For example, given the above matrix, the expression
[ a, a ]
produces the matrix
ans = 1 2 1 2 3 4 3 4
but the expression
[ a, 1 ]
produces the error
error: number of rows must match near line 13, column 6
(assuming that this expression was entered as the first thing on line 13, of course).
Commas and semicolons are not always required to separate matrix elements and rows. The expression
a = [ 1 2 3 4 ]
is equivalent to the one above.
Inside the square brackets that delimit a matrix expression, Octave looks at the surrounding context to determine whether spaces and newline characters should be converted into element and row separators, or simply ignored, so commands like
[ linspace (1, 2) ]
and
octave:13> a = [ 1 2 > 3 4 ]
will work. However, some possible sources of confusion remain. For example, in the expression
[ 1  1 ]
the `' is treated as a binary operator and the result is the scalar 0, but in the expression
[ 1 1 ]
the `' is treated as a unary operator and the result is the
vector [ 1 1 ]
.
Given a = 1
, the expression
[ 1 a' ]
results in the single quote character `'' being treated as a
transpose operator and the result is the vector [ 1 1 ]
, but the
expression
[ 1 a ' ]
produces the error message
error: unterminated string constant
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 builtin variable whitespace_in_literal_matrix
to
"ignore"
.
[ 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 identifiers 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 first 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 identifiers and `('. For
example, the expression
[m (1)]
will produce `3'. This is the way Octave has always behaved.
When you type a matrix or the name of a variable whose value is a matrix, Octave responds by printing the matrix in with neatly aligned rows and columns. If the rows of the matrix are too large to fit on the screen, Octave splits the matrix and displays a header before each section to indicate which columns are being displayed.
You can use the following variables to control the format of the output.
It is possible to achieve a wide range of output styles by using
different values of output_precision
and
output_max_field_width
. Reasonable combinations can be set using
the format
function. See section Basic Input and Output.
If the value of split_long_rows
is nonzero, Octave will display
the matrix in a series of smaller pieces, each of which can fit 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,10) ans = Columns 1 through 6: 0.75883 0.93290 0.40064 0.43818 0.94958 0.16467 0.75697 0.51942 0.40031 0.61784 0.92309 0.40201 Columns 7 through 10: 0.90174 0.11854 0.72313 0.73326 0.44672 0.94303 0.56564 0.82150
The default value of split_long_rows
is nonzero.
A matrix may have one or both dimensions zero, and operations on empty
matrices are handled as described by Carl de Boor in An Empty
Exercise, SIGNUM, Volume 25, pages 26, 1990 and C. N. Nett and W. M.
Haddad, in A SystemTheoretic Appropriate Realization of the Empty
Matrix Concept, IEEE Transactions on Automatic Control, Volume 38,
Number 5, May 1993. Briefly, given a scalar s
, and an m by
n matrix M(mxn)
, and an m by n empty matrix
[](mxn)
(with either one or both dimensions equal to zero), the
following are true:
s * [](mxn) = [](mxn) * s = [](mxn) [](mxn) + [](mxn) = [](mxn) [](0xm) * M(mxn) = [](0xn) M(mxn) * [](nx0) = [](mx0) [](mx0) * [](0xn) = 0(mxn)
By default, dimensions of the empty matrix are printed along with the empty matrix symbol, `[]'. For example:
octave:13> zeros (3, 0) ans = [](3x0)
The builtin variable print_empty_dimensions
controls this
behavior.
print_empty_dimensions
is nonzero, the
dimensions of empty matrices are printed along with the empty matrix
symbol, `[]'. For example, the expression
zeros (3, 0)
will print
ans = [](3x0)
Empty matrices may also be used in assignment statements as a convenient way to delete rows or columns of matrices. See section Assignment Expressions.
Octave will normally issue a warning if it finds an empty matrix in the
list of elements that make up another matrix. You can use the variable
empty_list_elements_ok
to suppress the warning or to treat it as
an error.
For example, if the value of empty_list_elements_ok
is
nonzero, 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"
.
A range is a convenient way to write a row vector with evenly spaced elements. A range constant is defined by the value of the first element in the range, an optional value for the increment between elements, and a maximum value which the elements of the range will not exceed. The base, increment, and limit are separated by colons (the `:' character) and may contain any arithmetic expressions and function calls. If the increment is omitted, it is assumed to be 1. For example, the range
1 : 5
defines the set of values `[ 1 2 3 4 5 ]', and the range
1 : 3 : 5
defines the set of values `[ 1 4 ]'.
Although a range constant specifies a row vector, Octave does not convert range constants to vectors unless it is necessary to do so. This allows you to write a constant like `1 : 10000' without using up 80,000 bytes of storage on a typical 32bit 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
defined by floating point values can produce surprising results because
Octave uses floating point arithmetic to compute the values in the
range. If it is important to include the endpoints of a range and the
number of elements is known, you should use the linspace
function
instead (see section Special Matrices).
Variables let you give names to values and refer to them later. You have already seen variables in many of the examples. The name of a variable must be a sequence of letters, digits and underscores, but it may not begin with a digit. Octave does not enforce a limit on the length of variable names, but it is seldom useful to have variables with names longer than about 30 characters. The following are all valid variable names
x x15 __foo_bar_baz__ fucnrdthsucngtagdjb
However, names like __foo_bar_baz__
that begin and end with two
underscores are understood to be reserved for internal use by Octave.
You should not use them in code you write, except to access Octave's
documented internal variables and builtin symbolic constants.
Case is significant in variable names. The symbols a
and
A
are distinct variables.
A variable name is a valid expression by itself. It represents the variable's current value. Variables are given new values with assignment operators and increment operators. See section Assignment Expressions.
A number of variables have special builtin meanings. For example,
PWD
holds the current working directory, and pi
names the
ratio of the circumference of a circle to its diameter. See section Builtin Variables, for a list of all the predefined variables. Some of these
builtin 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 do not have fixed types, so it is possible to first store a numeric value in a variable and then to later use the same name to hold a string value in the same program. Variables may not be used before they have been given a value. Doing so results in an error.
An index expression allows you to reference or extract selected elements of a matrix or vector.
Indices may be scalars, vectors, ranges, or the special operator `:', which may be used to select entire rows or columns.
Vectors are indexed using a single expression. Matrices require two
indices unless the value of the builtin variable
do_fortran_indexing
is nonzero, in which case matrices may
also be indexed by a single expression.
do_fortran_indexing
is nonzero, Octave allows
you to select elements of a twodimensional matrix using a single index
by treating the matrix as a single vector created from the columns of
the matrix. The default value is 0.
Given the matrix
a = [1, 2; 3, 4]
all of the following expressions are equivalent
a (1, [1, 2]) a (1, 1:2) a (1, :)
and select the first row of the matrix.
A special form of indexing may be used to select elements of a matrix or vector. If the indices are vectors made up of only ones and zeros, the result is a new matrix whose elements correspond to the elements of the index vector that are equal to one. For example,
a = [1, 2; 3, 4]; a ([1, 0], :)
selects the first row of the matrix `a'.
This operation can be useful for selecting elements of a matrix based on some condition, since the comparison operators return matrices of ones and zeros.
This special zeroone form of indexing leads to a conflict with the standard indexing operation. For example, should the following statements
a = [1, 2; 3, 4]; a ([1, 1], :)
return the original matrix, or the matrix formed by selecting the first
row twice? Although this conflict is not likely to arise very often in
practice, you may select the behavior you prefer by setting the builtin
variable prefer_zero_one_indexing
.
prefer_zero_one_indexing
is nonzero, Octave
will perform zeroone style indexing when there is a conflict with the
normal indexing rules. See section Index Expressions. For example, given a
matrix
a = [1, 2, 3, 4]
with prefer_zero_one_indexing
is set to nonzero, the
expression
a ([1, 1, 1, 1])
results in the matrix `[ 1 2 3 4 ]'. If the value of
prefer_zero_one_indexing
set to 0, the result would be
the matrix `[ 1 1 1 1 ]'.
In the first case, Octave is selecting each element corresponding to a `1' in the index vector. In the second, Octave is selecting the first element multiple times.
The default value for prefer_zero_one_indexing
is 0.
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 section Special Matrices.
prefer_column_vectors
is nonzero, operations like
for i = 1:10 a (i) = i; endfor
(for `a' previously undefined) produce column vectors. Otherwise, row vectors are preferred. The default value is 0.
If a variable is already defined to be a vector (a matrix with a single
row or column), the original orientation is respected, regardless of the
value of prefer_column_vectors
.
resize_on_range_error
is nonzero, expressions
like
for i = 1:10 a (i) = i; endfor
(for `a' previously undefined) 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 0, an error message is
printed and control is returned to the top level. The default value is
1.
Octave includes support for organizing data in structures. The current implementation uses an associative array with indices limited to strings, but the syntax is more like Cstyle structures. Here are some examples of using data structures in Octave.
Elements of structures can be of any value type. For example, the list of statements
octave:1> x.a = 1; x.b = [1, 2; 3, 4]; x.c = "string";
creates a structure with three elements. To print the value of the structure, you can type its name, just as for any other variable:
octave:2> x x = { a = 1 b = 1 2 3 4 c = string }
Note that Octave may print the elements in any order.
Structures may be copied.
octave:1> y = x y = { a = 1 b = 1 2 3 4 c = string }
Since structures are themselves values, structure elements may reference
other structures. The following statements change the value of the
element b
of the structure x
to be a data structure
containing the single element d
, which has a value of 3.
octave:1> x.b.d = 3 x.b.d = 3 octave:2> x.b ans = { d = 3 } octave:3> x x = { a = 1 b = { d = 3 } c = string }
Note that when Octave prints the value of a structure that contains other structures, only a few levels are displayed. For example,
octave:1> a.b.c.d.e = 1; octave:2> a a = { b = { c = <structure> } }
This prevents long and confusing output from large deeply nested structures.
struct_levels_to_print
. The default value is 2.
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 complexvalued argument, f
returns the data
structure containing the real and imaginary parts of the original
function argument.
octave:2> f (rand (3) + rand (3) * I); ans = { im = 0.26475 0.14828 0.18436 0.83669 re = 0.040239 0.242160 0.238081 0.402523 }
Function return lists can include structure elements, and they may be indexed like any other variable. For example,
octave:1> [ x.u, x.s(2:3,2:3), x.v ] = svd ([1, 2; 3, 4]) x.u = 0.40455 0.91451 0.91451 0.40455 x.s = 0.00000 0.00000 0.00000 0.00000 5.46499 0.00000 0.00000 0.00000 0.36597 x.v = 0.57605 0.81742 0.81742 0.57605
It is also possible to cycle through all the elements of a structure in
a loop, using a special form of the for
statement
(see section The for
Statement)
The following functions and variableare available to give you information about structures.
struct_elements
with an argument that is not a structure.
A function is a name for a particular calculation. Because it has
a name, you can ask for it by name at any point in the program. For
example, the function sqrt
computes the square root of a number.
A fixed set of functions are builtin, which means they are
available in every Octave program. The sqrt
function is one of
these. In addition, you can define your own functions.
See section Functions and Script Files, for information about how to do this.
The way to use a function is with a function call expression, which consists of the function name followed by a list of arguments in parentheses. The arguments are expressions which give the raw materials for the calculation that the function will do. When there is more than one argument, they are separated by commas. If there are no arguments, you can omit the parentheses, but it is a good idea to include them anyway, to clearly indicate that a function call was intended. Here are some examples:
sqrt (x^2 + y^2) # One argument ones (n, m) # Two arguments rand () # No arguments
Each function expects a particular number of arguments. For example, the
sqrt
function must be called with a single argument, the number
to take the square root of:
sqrt (argument)
Some of the builtin functions take a variable number of arguments, depending on the particular usage, and their behavior is different depending on the number of arguments supplied.
Like every other expression, the function call has a value, which is
computed by the function based on the arguments you give it. In this
example, the value of sqrt (argument)
is the square root of
the argument. A function can also have side effects, such as assigning
the values of certain variables or doing input or output operations.
Unlike most languages, functions in Octave may return multiple values. For example, the following statement
[u, s, v] = svd (a)
computes the singular value decomposition of the matrix `a' and assigns the three result matrices to `u', `s', and `v'.
The left side of a multiple assignment expression is itself a list of expressions, and is allowed to be a list of variable names or index expressions. See also section Index Expressions, and section Assignment Expressions.
In Octave, unlike Fortran, function arguments are passed by value, which means that each argument in a function call is evaluated and assigned to a temporary location in memory before being passed to the function. There is currently no way to specify that a function parameter should be passed by reference instead of by value. This means that it is impossible to directly alter the value of function parameter in the calling function. It can only change the local copy within the function body. For example, the function
function f (x, n) while (n > 0) disp (x); endwhile endfunction
displays the value of the first argument n times. In this function, the variable n is used as a temporary variable without having to worry that its value might also change in the calling function. Call by value is also useful because it is always possible to pass constants for any function parameter without first having to determine that the function will not attempt to modify the parameter.
The caller may use a variable as the expression for the argument, but the called function does not know this: it only knows what value the argument had. For example, given a function called as
foo = "bar"; fcn (foo)
you should not think of the argument as being "the variable
foo
." Instead, think of the argument as the string value,
"bar"
.
Even though Octave uses passbyvalue semantics for function arguments, values are not copied unnecessarily. For example,
x = rand (1000); f (x);
does not actually force two 1000 by 1000 element matrices to exist
unless the function f
modifies the value of its
argument. Then Octave must create a copy to avoid changing the
value outside the scope of the function f
, or attempting (and
probably failing!) to modify the value of a constant or the value of a
temporary result.
With some restrictions(3), recursive function calls are allowed. A recursive function is one which calls itself, either directly or indirectly. For example, here is an inefficient(4) way to compute the factorial of a given integer:
function retval = fact (n) if (n > 0) retval = n * fact (n1); 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 infinite 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 fixed in some future version of Octave by allowing users to specify a maximum allowable recursion depth.
A variable that has been declared global may be accessed from within a function body without having to pass it as a formal parameter.
A variable may be declared global using a global
declaration
statement. The following statements are all global declarations.
global a global b = 2 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.
warn_comma_in_global_decl
is nonzero, a
warning is issued for statements 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 nonzero.
The following identifiers are keywords, and may not be used as variable or function names:
all_va_args endwhile break for catch function continue global else gplot elseif gsplot end if end_try_catch return end_unwind_protect try endfor unwind_protect endfunction unwind_protect_cleanup endif while
The following commandlike functions are also reserved, and may not be used as variable or function names:
casesen echo load show cd edit_history ls type chdir format more which clear help run_history who diary history save whos dir hold set
The following arithmetic operators are available, and work on scalars and matrices.
x + y
x .+ y
+
.
x  y
x . y

.
x * y
x .* y
x / y
(inverse (y') * x')'but it is computed without forming the inverse of `y''. If the system is not square, or if the coefficient matrix is singular, a minimum norm solution is computed.
x ./ y
x \ y
inverse (x) * ybut it is computed without forming the inverse of `x'. If the system is not square, or if the coefficient matrix is singular, a minimum norm solution is computed.
x .\ y
x ^ y
x ** y
x .^ y
x .** y
x
+x
x'
conj (x.')
x.'
Note that because Octave's element by element operators begin with a `.', there is a possible ambiguity for statements like
1./m
because the period could be interpreted either as part of the constant or as part of the operator. To resolve this conflict, Octave treats the expression as if you had typed
(1) ./ m
and not
(1.) / m
Although this is inconsistent with the normal behavior of Octave's lexer, which usually prefers to break the input into tokens by preferring the longest possible match at any given point, it is more useful in this case.
warn_divide_by_zero
is nonzero, a warning
is issued when Octave encounters a division by zero. If the value is
0, the warning is omitted. The default value is 1.
Comparison operators compare numeric values for relationships such as equality. They are written using relational operators, which are a superset of those in C.
All of Octave's comparison operators return a value of 1 if the comparison is true, or 0 if it is false. For matrix values, they all work on an elementbyelement basis. For example, evaluating the expression
[1, 2; 3, 4] == [1, 3; 2, 4]
returns the result
ans = 1 0 0 1
x < y
x <= y
x == y
x >= y
x > y
x != y
x ~= y
x <> 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 specified condition"
String comparisons should be performed with the strcmp
function,
not with the comparison operators listed above.
See section String Functions.
An elementbyelement boolean expression is a combination of comparison expressions or matching expressions, using the boolean operators "or" (`'), "and" (`&'), and "not" (`!'), along with parentheses to control nesting. The truth of the boolean expression is computed by combining the truth values of the corresponding elements of the component expressions. A value is considered to be false if it is zero, and true otherwise.
Elementbyelement boolean expressions can be used wherever comparison
expressions can be used. They can be used in if
and while
statements. However, before being used in the condition of an if
or while
statement, an implicit conversion from a matrix value to
a scalar value occurs using the equivalent of
all (all (x))
. That is, a value used as the condition in an
if
or while
statement is only true if all of its
elements are nonzero.
Like comparison operations, each element of an elementbyelement boolean expression also has a numeric value (1 if true, 0 if false) that comes into play if the result of the boolean expression is stored in a variable, or used in arithmetic.
Here are descriptions of the three elementbyelement boolean operators.
boolean1 & boolean2
boolean1  boolean2
! boolean
~ boolean
For matrix operands, these operators work on an elementbyelement 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 elementbyelement boolean operators, both subexpressions boolean1 and boolean2 are evaluated before computing the result. This can make a difference when the expressions have side effects. For example, in the expression
a & b++
the value of the variable b is incremented even if the variable a is zero.
This behavior is necessary for the boolean operators to work as described for matrixvalued operands.
Combined with the implicit conversion to scalar values in if
and
while
conditions, Octave's elementbyelement boolean operators
are often sufficient for performing most logical operations. However,
it is sometimes desirable to stop evaluating a boolean expression as
soon as the overall truth value can be determined. Octave's
shortcircuit boolean operators work this way.
boolean1 && boolean2
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
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
a && b++
the value of the variable b is only incremented if the variable a is nonzero.
This can be used to write somewhat more concise code. For example, it is possible write
function f (a, b, c) if (nargin > 2 && isstr (c)) ...
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)) ...
An assignment is an expression that stores a new value into a
variable. For example, the following expression assigns the value 1 to
the variable z
:
z = 1
After this expression is executed, the variable z
has the value 1.
Whatever old value z
had before the assignment is forgotten.
Assignments can store string values also. For example, the following
expression would store the value "this food is good"
in the
variable message
:
thing = "food" predicate = "good" message = [ "this " , thing , " is " , predicate ]
(This also illustrates concatenation of strings.)
The `=' sign is called an assignment operator. It is the simplest assignment operator because the value of the righthand operand is stored unchanged.
Most operators (addition, concatenation, and so on) have no effect except to compute a value. If you ignore the value, you might as well not use the operator. An assignment operator is different. It does produce a value, but even if you ignore the value, the assignment still makes itself felt through the alteration of the variable. We call this a side effect.
The lefthand operand of an assignment need not be a variable (see section Variables). It can also be an element of a matrix (see section Index Expressions) or a list of return values (see section Calling Functions). These are all called lvalues, which means they can appear on the lefthand side of an assignment operator. The righthand operand may be any expression. It produces the new value which the assignment stores in the specified variable, matrix element, or list of return values.
It is important to note that variables do not have permanent types.
The type of a variable is simply the type of whatever value it happens
to hold at the moment. In the following program fragment, the variable
foo
has a numeric value at first, and a string value later on:
octave:13> foo = 1 foo = 1 octave:13> foo = "bar" foo = bar
When the second assignment gives foo
a string value, the fact that
it previously had a numeric value is forgotten.
Assigning an empty matrix `[]' works in most cases to allow you to delete rows or columns of matrices and vectors. See section Empty Matrices. For example, given a 4 by 5 matrix A, the assignment
A (3, :) = []
deletes the third row of A, and the assignment
A (:, 1:2:5) = []
deletes the first, third, and fifth columns.
An assignment is an expression, so it has a value. Thus, z = 1
as an expression has the value 1. One consequence of this is that you
can write multiple assignments together:
x = y = z = 0
stores the value 0 in all three variables. It does this because the
value of z = 0
, which is 0, is stored into y
, and then
the value of y = z = 0
, which is 0, is stored into x
.
This is also true of assignments to lists of values, so the following is a valid expression
[a, b, c] = [u, s, v] = svd (a)
that is exactly equivalent to
[u, s, v] = svd (a) a = u b = s c = v
In expressions like this, the number of values in each part of the expression need not match. For example, the expression
[a, b, 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 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 oneshot program, you should rewrite
it to get rid of such nesting of assignments. This is never very hard.
Increment operators increase or decrease the value of a variable by 1. The operator to increment a variable is written as `++'. It may be used to increment a variable either before or after taking its value.
For example, to preincrement the variable x, you would write
++x
. This would add one to x and then return the new
value of x as the result of the expression. It is exactly the
same as the expression x = x + 1
.
To postincrement a variable x, you would write x++
.
This adds one to the variable x, but returns the value that
x had prior to incrementing it. For example, if x is equal
to 2, the result of the expression x++
is 2, and the new
value of x is 3.
For matrix and vector arguments, the increment and decrement operators work on each element of the operand.
Here is a list of all the increment and decrement expressions.
++x
x = x + 1
.
x
x = x  1
.
x++
x
It is not currently possible to increment index expressions. For
example, you might expect that the expression v(4)++
would
increment the fourth element of the vector v, but instead it
results in a parse error. This problem may be fixed in a future
release of Octave.
Operator precedence determines how operators are grouped, when
different operators appear close by in one expression. For example,
`*' has higher precedence than `+'. Thus, the expression
a + b * c
means to multiply b
and c
, and then add
a
to the product (i.e., a + (b * c)
).
You can overrule the precedence of the operators by using parentheses. You can think of the precedence rules as saying where the parentheses are assumed if you do not write parentheses yourself. In fact, it is wise to use parentheses whenever you have an unusual combination of operators, because other people who read the program may not remember what the precedence is in this case. You might forget as well, and then you too could make a mistake. Explicit parentheses will help prevent any such mistake.
When operators of equal precedence are used together, the leftmost
operator groups first, except for the assignment, 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 prefix unary operators is important when another
operator follows the operand. For example, x^2
means
(x^2)
, because `' has lower precedence than `^'.
Here is a table of the operators in Octave, in order of increasing precedence.
statement separators
assignment
logical "or" and "and"
elementwise "or" and "and"
relational
colon
add, subtract
multiply, divide
transpose
unary plus, minus, increment, decrement, and "not"
exponentiation
Go to the first, previous, next, last section, table of contents.