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.

Index Expressions
=================

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 index expression.  Matrices may be indexed using one or two indices.  When using a single index expression, the elements of the matrix are taken in column-first order; the dimensions of the output match those of the index expression.  For example,

     a (2)       # a scalar
     a (1:2)     # a row vector
     a ([1; 2])  # a column vector

As a special case, when a colon is used as a single index, the output is a column vector containing all the elements of the vector or matrix. For example:

     a (:)       # a column vector

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.

In general, an array with n dimensions can be indexed using m indices.  If n == m, each index corresponds to its respective dimension. The set of index tuples determining the result is formed by the Cartesian product of the index vectors (or ranges or scalars).  If n < m, then the array is padded by trailing singleton dimensions.  If n > m, the last n-m+1 dimensions are folded into a single dimension with extent equal to product of extents of the original dimensions.

Indexing a scalar with a vector of ones can be used to create a vector the same size as the index vector, with each element equal to the value of the original scalar.  For example, the following statements

     a = 13;
     a (ones (1, 4))

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 (ones (1, 2), ones (1, 3))

create a 2 by 3 matrix with all elements equal to 13.

The last example could also be written as

     13 (ones (2, 3))

It should be, noted that ones (1, n) (a row vector of ones) results in a range (with zero increment), and is therefore more efficient when used in index expression than other forms of ones.  In particular, when r is a row vector, the expressions

       r(ones (1, n), :)

       r(ones (n, 1), :)

will produce identical results, but the first one will be significantly faster, at least for r and n large enough.  The reason is that in the first case the index is kept in a compressed form, which allows Octave to choose a more efficient algorithm to handle the expression.

In general, for an user unaware of these subtleties, it is best to use the function repmat for spreading arrays into bigger ones.

It is also possible to create a matrix with different values.  The following example creates a 10 dimensional row vector a containing the values a(i) = sqrt(i).

     for i = 1:10
       a(i) = sqrt (i);
     endfor

Note that it is quite inefficient to create a vector using a loop like the one shown in the example above.  In this particular case, it would have been much more efficient to use the expression

     a = sqrt (1:10);

thus avoiding the loop entirely.  In cases where a loop is still required, or a number of values must be combined to form a larger matrix, it is generally much faster to set the size of the matrix first, and then insert elements using indexing commands.  For example, given a matrix a,

     [nr, nc] = size (a);
     x = zeros (nr, n * nc);
     for i = 1:n
       x(:,(i-1)*nc+1:i*nc) = a;
     endfor

is considerably faster than

     x = a;
     for i = 1:n-1
       x = [x, a];
     endfor

particularly for large matrices because Octave does not have to repeatedly resize the result.

(sub2ind)

(ind2sub)

(isindex)

(allow_noninteger_range_as_index)

Calling Functions
=================

A function is a name for a particular calculation.  Because it has a name, you can ask for it by name at any point in the program.  For example, the function sqrt computes the square root of a number.

A fixed set of functions are built-in, which means they are available in every Octave program.  The sqrt function is one of these.  In addition, you can define your own functions. See Functions and Scripts, for information about how to do this.

The way to use a function is with a function call expression, which consists of the function name followed by a list of arguments in parentheses.  The arguments are expressions which give the raw materials for the calculation that the function will do.  When there is more than one argument, they are separated by commas.  If there are no arguments, you can omit the parentheses, but it is a good idea to include them anyway, to clearly indicate that a function call was intended.  Here are some examples:

     sqrt (x^2 + y^2)      # One argument
     ones (n, m)           # Two arguments
     rand ()               # No arguments

Each function expects a particular number of arguments.  For example, the sqrt function must be called with a single argument, the number to take the square root of:

     sqrt (ARGUMENT)

Some of the built-in functions take a variable number of arguments, depending on the particular usage, and their behavior is different depending on the number of arguments supplied.

Like every other expression, the function call has a value, which is computed by the function based on the arguments you give it.  In this example, the value of sqrt (ARGUMENT) is the square root of the argument.  A function can also have side effects, such as assigning the values of certain variables or doing input or output operations.

Unlike most languages, functions in Octave may return multiple values. For example, the following statement

     [u, s, v] = svd (a)

computes the singular value decomposition of the matrix a and assigns the three result matrices to u, s, and v.

The left side of a multiple assignment expression is itself a list of expressions, and is allowed to be a list of variable names or index expressions.  See also Index Expressions, and Assignment Ops.

Call by Value
-------------

In Octave, unlike Fortran, function arguments are passed by value, which means that each argument in a function call is evaluated and assigned to a temporary location in memory before being passed to the function. There is currently no way to specify that a function parameter should be passed by reference instead of by value.  This means that it is impossible to directly alter the value of a function parameter in the calling function.  It can only change the local copy within the function body.  For example, the function

     function f (x, n)
       while (n-- > 0)
         disp (x);
       endwhile
     endfunction

displays the value of the first argument N times.  In this function, the variable N is used as a temporary variable without having to worry that its value might also change in the calling function.  Call by value is also useful because it is always possible to pass constants for any function parameter without first having to determine that the function will not attempt to modify the parameter.

The caller may use a variable as the expression for the argument, but the called function does not know this: it only knows what value the argument had.  For example, given a function called as

     foo = "bar";
     fcn (foo)

you should not think of the argument as being ``the variable foo.''  Instead, think of the argument as the string value, "bar".

Even though Octave uses pass-by-value semantics for function arguments, values are not copied unnecessarily.  For example,

     x = rand (1000);
     f (x);

does not actually force two 1000 by 1000 element matrices to exist unless the function f modifies the value of its argument.  Then Octave must create a copy to avoid changing the value outside the scope of the function f, or attempting (and probably failing!) to modify the value of a constant or the value of a temporary result.

Recursion
---------

With some restrictions (Some of Octave's functions are implemented in terms of functions that cannot be called recursively. For example, the ODE solver lsode is ultimately implemented in a Fortran subroutine that cannot be called recursively, so lsode should not be called either directly or indirectly from within the user-supplied function that lsode requires.  Doing so will result in an error.), recursive function calls are allowed.  A recursive function is one which calls itself, either directly or indirectly.  For example, here is an inefficient (It would be much better to use prod (1:n), or gamma (n+1) instead, after first checking to ensure that the value n is actually a positive integer.) way to compute the factorial of a given integer:

     function retval = fact (n)
       if (n > 0)
         retval = n * fact (n-1);
       else
         retval = 1;
       endif
     endfunction

This function is recursive because it calls itself directly.  It eventually terminates because each time it calls itself, it uses an argument that is one less than was used for the previous call.  Once the argument is no longer greater than zero, it does not call itself, and the recursion ends.

The built-in variable max_recursion_depth specifies a limit to the recursion depth and prevents Octave from recursing infinitely.

(max_recursion_depth)

Arithmetic Operators
====================

The following arithmetic operators are available, and work on scalars and matrices.

X + Y
     Addition.  If both operands are matrices, the number of rows and columns must both agree.  If one operand is a scalar, its value is added to all the elements of the other operand.

X .+ Y
     Element by element addition.  This operator is equivalent to +.

X - Y
     Subtraction.  If both operands are matrices, the number of rows and columns of both must agree.

X .- Y
     Element by element subtraction.  This operator is equivalent to -.

X * Y
     Matrix multiplication.  The number of columns of X must agree with the number of rows of Y.

X .* Y
     Element by element multiplication.  If both operands are matrices, the number of rows and columns must both agree.

X / Y
     Right division.  This is conceptually equivalent to the expression

          (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
     Element by element right division.

X \ Y
     Left division.  This is conceptually equivalent to the expression

          inverse (x) * y

     but it is computed without forming the inverse of X.

     If the system is not square, or if the coefficient matrix is singular, a minimum norm solution is computed.

X .\ Y
     Element by element left division.  Each element of Y is divided by each corresponding element of X.

X ^ Y
X ** Y
     Power operator.  If X and Y are both scalars, this operator returns X raised to the power Y.  If X is a scalar and Y is a square matrix, the result is computed using an eigenvalue expansion.  If X is a square matrix, the result is computed by repeated multiplication if Y is an integer, and by an eigenvalue expansion if Y is not an integer.  An error results if both X and Y are matrices.

     The implementation of this operator needs to be improved.

X .^ Y
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 effect 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 expression

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

(ctranspose)

(ldivide)

(minus)

(mldivide)

(mpower)

(mrdivide)

(mtimes)

(plus)

(power)

(rdivide)

(times)

(transpose)

(uminus)

(uplus)

Comparison Operators
====================

Comparison operators compare numeric values for relationships such as equality.  They are written using relational operators.

All of Octave's comparison operators return a value of 1 if the comparison is true, or 0 if it is false.  For matrix values, they all work on an element-by-element basis.  For example:

     [1, 2; 3, 4] == [1, 3; 2, 4]
          =>  1  0
              0  1

If one operand is a scalar and the other is a matrix, the scalar is compared to each element of the matrix in turn, and the result is the same size as the matrix.

X < Y
     True if X is less than Y.

X <= Y
     True if X is less than or equal to Y.

X == Y
     True if X is equal to Y.

X >= Y
     True if X is greater than or equal to Y.

X > Y
     True if X is greater than Y.

X != Y
X ~= Y
     True if X is not equal to Y.

For complex numbers, the following ordering is defined: Z1 < Z2 iff

       abs(Z1) < abs(Z2)
       || (abs(Z1) == abs(Z2) && arg(Z1) < arg(Z2))

This is consistent with the ordering used by max, min and sort, but is not consistent with MATLAB, which only compares the real parts.

String comparisons may also be performed with the strcmp function, not with the comparison operators listed above. See Strings.

(eq)

(ge)

(gt)

(isequal)

(isequalwithequalnans)

(le)

(lt)

(ne)

Boolean Expressions
===================

Element-by-element Boolean Operators
------------------------------------

An element-by-element boolean expression is a combination of comparison expressions using the boolean operators ``or'' (|), ``and'' (&), and ``not'' (!), along with parentheses to control nesting.  The truth of the boolean expression is computed by combining the truth values of the corresponding elements of the component expressions.  A value is considered to be false if it is zero, and true otherwise.

Element-by-element boolean expressions can be used wherever comparison expressions can be used.  They can be used in if and while statements.  However, a matrix value used as the condition in an if or while statement is only true if all of its elements are nonzero.

Like comparison operations, each element of an element-by-element boolean expression also has a numeric value (1 if true, 0 if false) that comes into play if the result of the boolean expression is stored in a variable, or used in arithmetic.

Here are descriptions of the three element-by-element boolean operators.

BOOLEAN1 & BOOLEAN2
     Elements of the result are true if both corresponding elements of BOOLEAN1 and BOOLEAN2 are true.

BOOLEAN1 | BOOLEAN2
     Elements of the result are true if either of the corresponding elements of BOOLEAN1 or BOOLEAN2 is true.

! BOOLEAN
~ BOOLEAN
     Each element of the result is true if the corresponding element of BOOLEAN is false.

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 difference when the expressions have side effects.  For example, in the expression

     a & b++

the value of the variable B is incremented even if the variable A is zero.

This behavior is necessary for the boolean operators to work as described for matrix-valued operands.

(and)

(not)

(or)

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 sufficient for performing most logical operations.  However, it is sometimes desirable to stop evaluating a boolean expression as soon as the overall truth value can be determined.  Octave's short-circuit boolean operators work this way.

BOOLEAN1 && BOOLEAN2
     The expression BOOLEAN1 is evaluated and converted to a scalar using the equivalent of the operation all (BOOLEAN1(:)). If it is false, the result of the overall expression is 0.  If it is true, the expression BOOLEAN2 is evaluated and converted to a scalar using the equivalent of the operation all (BOOLEAN1(:)).  If it is true, the result of the overall expression is 1.  Otherwise, the result of the overall expression is 0.

     Warning: there is one exception to the rule of evaluating all (BOOLEAN1(:)), which is when boolean1 is the empty matrix.  The truth value of an empty matrix is always false so [] && true evaluates to false even though all ([]) is true.

BOOLEAN1 || BOOLEAN2
     The expression BOOLEAN1 is evaluated and converted to a scalar using the equivalent of the operation all (BOOLEAN1(:)). If it is true, the result of the overall expression is 1.  If it is false, the expression BOOLEAN2 is evaluated and converted to a scalar using the equivalent of the operation all (BOOLEAN1(:)).  If it is true, the result of the overall expression is 1.  Otherwise, the result of the overall expression is 0.

     Warning: the truth value of an empty matrix is always false, see the previous list item for details.

The fact that both operands may not be evaluated before determining the overall truth value of the expression can be important.  For example, in the expression

     a && b++

the value of the variable B is only incremented if the variable A is nonzero.

This can be used to write somewhat more concise code.  For example, it is possible write

     function f (a, b, c)
       if (nargin > 2 && ischar (c))
         ...

instead of having to use two if statements to avoid attempting to evaluate an argument that doesn't exist.  For example, without the short-circuit feature, it would be necessary to write

     function f (a, b, c)
       if (nargin > 2)
         if (ischar (c))
           ...

Writing

     function f (a, b, c)
       if (nargin > 2 & ischar (c))
         ...

would result in an error if f were called with one or two arguments because Octave would be forced to try to evaluate both of the operands for the operator &.

MATLAB has special behavior that allows the operators & and | to short-circuit when used in the truth expression for if and while statements.  The Octave parser may be instructed to behave in the same manner, but it's use is strongly discouraged.

(do_braindead_shortcircuit_evaluation)

Finally, the ternary operator (?:) is not supported in Octave.  If short-circuiting is not important, it can be replaced by the ifelse function.

(merge)

Assignment Expressions
======================

An assignment is an expression that stores a new value into a variable.  For example, the following expression assigns the value 1 to the variable z:

     z = 1

After this expression is executed, the variable z has the value 1. Whatever old value z had before the assignment is forgotten. The = sign is called an assignment operator.

Assignments can store string values also.  For example, the following expression would store the value "this food is good" in the variable message:

     thing = "food"
     predicate = "good"
     message = [ "this " , thing , " is " , predicate ]

(This also illustrates concatenation of strings.)

Most operators (addition, concatenation, and so on) have no effect except to compute a value.  If you ignore the value, you might as well not use the operator.  An assignment operator is different.  It does produce a value, but even if you ignore the value, the assignment still makes itself felt through the alteration of the variable.  We call this a side effect.

The left-hand operand of an assignment need not be a variable (see Variables).  It can also be an element of a matrix (see Index Expressions) or a list of return values (see Calling Functions).  These are all called lvalues, which means they can appear on the left-hand side of an assignment operator. The right-hand operand may be any expression.  It produces the new value which the assignment stores in the specified variable, matrix element, or list of return values.

It is important to note that variables do not have permanent types. The type of a variable is simply the type of whatever value it happens to hold at the moment.  In the following program fragment, the variable foo has a numeric value at first, and a string value later on:

     octave:13> foo = 1
     foo = 1
     octave:13> foo = "bar"
     foo = bar

When the second assignment gives foo a string value, the fact that it previously had a numeric value is forgotten.

Assignment of a scalar to an indexed matrix sets all of the elements that are referenced by the indices to the scalar value.  For example, if a is a matrix with at least two columns,

     a(:, 2) = 5

sets all the elements in the second column of a to 5.

Assigning an empty matrix [] works in most cases to allow you to delete rows or columns of matrices and vectors.  See Empty Matrices. For example, given a 4 by 5 matrix A, the assignment

     A (3, :) = []

deletes the third row of A, and the assignment

     A (:, 1:2:5) = []

deletes the first, third, and fifth columns.

An assignment is an expression, so it has a value.  Thus, z = 1 as an expression has the value 1.  One consequence of this is that you can write multiple assignments together:

     x = y = z = 0

stores the value 0 in all three variables.  It does this because the value of z = 0, which is 0, is stored into y, and then the value of y = z = 0, which is 0, is stored into x.

This is also true of assignments to lists of values, so the following is a valid expression

     [a, b, c] = [u, s, v] = svd (a)

that is exactly equivalent to

     [u, s, v] = svd (a)
     a = u
     b = s
     c = v

In expressions like this, the number of values in each part of the expression need not match.  For example, the expression

     [a, b] = [u, s, v] = svd (a)

is equivalent to

     [u, s, v] = svd (a)
     a = u
     b = s

The number of values on the left side of the expression can, however, not exceed the number of values on the right side.  For example, the following will produce an error.

     [a, b, c, d] = [u, s, v] = svd (a);
     -| error: element number 4 undefined in return list

The symbol ~ may be used as a placeholder in the list of lvalues, indicating that the corresponding return value should be ignored and not stored anywhere:

     [~, s, v] = svd (a);

This is cleaner and more memory efficient than using a dummy variable. The nargout value for the right-hand side expression is not affected. If the assignment is used as an expression, the return value is a comma-separated list with the ignored values dropped.

A very common programming pattern is to increment an existing variable with a given value, like this

     a = a + 2;

This can be written in a clearer and more condensed form using the += operator

     a += 2;

Similar operators also exist for subtraction (-=), multiplication (*=), and division (/=).  An expression of the form

     EXPR1 OP= EXPR2

is evaluated as

     EXPR1 = (EXPR1) OP (EXPR2)

where OP can be either +, -, *, or /. So, the expression

     a *= b+1

is evaluated as

     a = a * (b+1)

and not

     a = a * b + 1

You can use an assignment anywhere an expression is called for.  For example, it is valid to write x != (y = 1) to set y to 1 and then test whether x equals 1.  But this style tends to make programs hard to read.  Except in a one-shot program, you should rewrite it to get rid of such nesting of assignments.  This is never very hard.

Increment Operators
===================

Increment operators increase or decrease the value of a variable by 1.  The operator to increment a variable is written as ++.  It may be used to increment a variable either before or after taking its value.

For example, to pre-increment the variable X, you would write ++X.  This would add one to X and then return the new value of X as the result of the expression.  It is exactly the same as the expression X = X + 1.

To post-increment a variable X, you would write X++. This adds one to the variable X, but returns the value that X had prior to incrementing it.  For example, if X is equal to 2, the result of the expression X++ is 2, and the new value of X is 3.

For matrix and vector arguments, the increment and decrement operators work on each element of the operand.

Here is a list of all the increment and decrement expressions.

++X
     This expression increments the variable X.  The value of the expression is the new value of X.  It is equivalent to the expression X = X + 1.

--X
     This expression decrements the variable X.  The value of the expression is the new value of X.  It is equivalent to the expression X = X - 1.

X++
     This expression causes the variable X to be incremented.  The value of the expression is the old value of X.

X--
     This expression causes the variable X to be decremented.  The value of the expression is the old value of X.

Operator Precedence
===================

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
     =, +=, -=, *=,/=.  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
     ^, **, .^, .**.