Numeric Data Types
******************

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 by default numeric constants are represented within Octave in double-precision floating point format (complex constants are stored as pairs of double-precision floating point values).  It is, however, possible to represent real integers as described in Integer Data Types.  Here are some examples of real-valued numeric constants, which all have the same value:

     105
     1.05e+2
     1050e-1

To specify complex constants, you can write an expression of the form

     3 + 4i
     3.0 + 4.0i
     0.3e1 + 40e-1i

all of which are equivalent.  The letter i in the previous example stands for the pure imaginary constant, defined as sqrt (-1).

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:

       syntax error

     >>> 3 + 4 i
               ^

You may also use j, I, or J in place of the i above.  All four forms are equivalent.

(double)

(complex)

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

             /      \
             | 1  2 |
       a  =  |      |
             | 3  4 |
             \      /

Elements of a matrix may be arbitrary expressions, provided that the dimensions all make sense when combining the various pieces.  For example, given the above matrix, the expression

     [ a, a ]

produces the matrix

     ans =

       1  2  1  2
       3  4  3  4

but the expression

     [ a, 1 ]

produces the error

     error: number of rows must match (1 != 2) near line 13, column 6

(assuming that this expression was entered as the first thing on line 13, of course).

Inside the square brackets that delimit a matrix expression, Octave looks at the surrounding context to determine whether spaces and newline characters should be converted into element and row separators, or simply ignored, so an expression like

     a = [ 1 2
           3 4 ]

will work.  However, some possible sources of confusion remain.  For example, in the expression

     [ 1 - 1 ]

the - is treated as a binary operator and the result is the scalar 0, but in the expression

     [ 1 -1 ]

the - is treated as a unary operator and the result is the vector [ 1, -1 ].  Similarly, the expression

     [ sin (pi) ]

will be parsed as

     [ sin, (pi) ]

and will result in an error since the sin function will be called with no arguments.  To get around this, you must omit the space between sin and the opening parenthesis, or enclose the expression in a set of parentheses:

     [ (sin (pi)) ]

Whitespace surrounding the single quote character (', used as a transpose operator and for delimiting character strings) can also cause confusion.  Given a = 1, the expression

     [ 1 a' ]

results in the single quote character being treated as a transpose operator and the result is the vector [ 1, 1 ], but the expression

     [ 1 a ' ]

produces the error message

     parse error:

       syntax error

     >>> [ 1 a ' ]
                   ^

because not doing so would cause trouble when parsing the valid expression

     [ a 'foo' ]

For clarity, it is probably best to always use commas and semicolons to separate matrix elements and rows.

The maximum number of elements in a matrix is fixed when Octave is compiled. The allowable number can be queried with the function sizemax.  Note that other factors, such as the amount of memory available on your machine, may limit the maximum size of matrices to something smaller.

(sizemax)

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.

(output_max_field_width)

(output_precision)

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 Basic Input and Output.

(split_long_rows)

Octave automatically switches to scientific notation when values become very large or very small.  This guarantees that you will see several significant figures for every value in a matrix.  If you would prefer to see all values in a matrix printed in a fixed point format, you can set the built-in variable fixed_point_format to a nonzero value.  But doing so is not recommended, because it can produce output that can easily be misinterpreted.

(fixed_point_format)

Empty Matrices
--------------

A matrix may have one or both dimensions zero, and operations on empty matrices are handled as described by Carl de Boor in An Empty Exercise, SIGNUM, Volume 25, pages 2-6, 1990 and C. N. Nett and W. M. Haddad, in A System-Theoretic Appropriate Realization of the Empty Matrix Concept, IEEE Transactions on Automatic Control, Volume 38, Number 5, May 1993. Briefly, given a scalar S, an M by N matrix M(mxn), and an M by N empty matrix [](mxn) (with either one or both dimensions equal to zero), the following are true:

     s * [](mxn) = [](mxn) * s = [](mxn)

         [](mxn) + [](mxn) = [](mxn)

         [](0xm) *  M(mxn) = [](0xn)

          M(mxn) * [](nx0) = [](mx0)

         [](mx0) * [](0xn) =  0(mxn)

By default, dimensions of the empty matrix are printed along with the empty matrix symbol, [].  The built-in variable print_empty_dimensions controls this behavior.

(print_empty_dimensions)

Empty matrices may also be used in assignment statements as a convenient way to delete rows or columns of matrices. See Assignment Expressions.

When Octave parses a matrix expression, it examines the elements of the list to determine whether they are all constants.  If they are, it replaces the list with a single matrix constant.

Ranges
======

A range is a convenient way to write a row vector with evenly spaced elements.  A range expression is defined by the value of the first element in the range, an optional value for the increment between elements, and a maximum value which the elements of the range will not exceed.  The base, increment, and limit are separated by colons (the : character) and may contain any arithmetic expressions and function calls.  If the increment is omitted, it is assumed to be 1. For example, the range

     1 : 5

defines the set of values [ 1, 2, 3, 4, 5 ], and the range

     1 : 3 : 5

defines the set of values [ 1, 4 ].

Although a range constant specifies a row vector, Octave does not convert range constants to vectors unless it is necessary to do so. This allows you to write a constant like 1 : 10000 without using 80,000 bytes of storage on a typical 32-bit workstation.

A common example of when it does become necessary to convert ranges into vectors occurs when they appear within a vector (i.e., inside square brackets).  For instance, whereas

     x = 0 : 0.1 : 1;

defines X to be a variable of type range and occupies 24 bytes of memory, the expression

     y = [ 0 : 0.1 : 1];

defines Y to be of type matrix and occupies 88 bytes of memory.

Note that the upper (or lower, if the increment is negative) bound on the range is not always included in the set of values, and that ranges defined by floating point values can produce surprising results because Octave uses floating point arithmetic to compute the values in the range.  If it is important to include the endpoints of a range and the number of elements is known, you should use the linspace function instead (see Special Utility Matrices).

When adding a scalar to a range, subtracting a scalar from it (or subtracting a range from a scalar) and multiplying by scalar, Octave will attempt to avoid unpacking the range and keep the result as a range, too, if it can determine that it is safe to do so.  For instance, doing

     a = 2*(1:1e7) - 1;

will produce the same result as 1:2:2e7-1, but without ever forming a vector with ten million elements.

Using zero as an increment in the colon notation, as 1:0:1 is not allowed, because a division by zero would occur in determining the number of range elements.  However, ranges with zero increment (i.e., all elements equal) are useful, especially in indexing, and Octave allows them to be constructed using the built-in function ones.  Note that because a range must be a row vector, ones (1, 10) produces a range, while ones (10, 1) does not.

When Octave parses a range expression, it examines the elements of the expression to determine whether they are all constants.  If they are, it replaces the range expression with a single range constant.

Single Precision Data Types
===========================

Octave includes support for single precision data types, and most of the functions in Octave accept single precision values and return single precision answers.  A single precision variable is created with the single function.

(single)

for example:

     sngl = single (rand (2, 2))
          => sngl =
             0.37569   0.92982
             0.11962   0.50876
     class (sngl)
         => single

Many functions can also return single precision values directly.  For example

     ones (2, 2, "single")
     zeros (2, 2, "single")
     eye (2, 2,  "single")
     rand (2, 2, "single")
     NaN (2, 2, "single")
     NA (2, 2, "single")
     Inf (2, 2, "single")

will all return single precision matrices.

Integer Data Types
==================

Octave supports integer matrices as an alternative to using double precision.  It is possible to use both signed and unsigned integers represented by 8, 16, 32, or 64 bits.  It should be noted that most computations require floating point data, meaning that integers will often change type when involved in numeric computations.  For this reason integers are most often used to store data, and not for calculations.

In general most integer matrices are created by casting existing matrices to integers.  The following example shows how to cast a matrix into 32 bit integers.

     float = rand (2, 2)
          => float = 0.37569   0.92982
                     0.11962   0.50876
     integer = int32 (float)
          => integer = 0  1
                       0  1

As can be seen, floating point values are rounded to the nearest integer when converted.

(isinteger)

(int8)

(uint8)

(int16)

(uint16)

(int32)

(uint32)

(int64)

(uint64)

(intmax)

(intmin)

Integer Arithmetic
------------------

While many numerical computations can't be carried out in integers, Octave does support basic operations like addition and multiplication on integers.  The operators +, -, .*, and ./ work on integers of the same type.  So, it is possible to add two 32 bit integers, but not to add a 32 bit integer and a 16 bit integer.

When doing integer arithmetic one should consider the possibility of underflow and overflow.  This happens when the result of the computation can't be represented using the chosen integer type.  As an example it is not possible to represent the result of 10 - 20 when using unsigned integers.  Octave makes sure that the result of integer computations is the integer that is closest to the true result.  So, the result of 10 - 20 when using unsigned integers is zero.

When doing integer division Octave will round the result to the nearest integer.  This is different from most programming languages, where the result is often floored to the nearest integer.  So, the result of int32 (5) ./ int32 (8) is 1.

(idivide)

Bit Manipulations
=================

Octave provides a number of functions for the manipulation of numeric values on a bit by bit basis.  The basic functions to set and obtain the values of individual bits are bitset and bitget.

(bitset)

(bitget)

The arguments to all of Octave's bitwise operations can be scalar or arrays, except for bitcmp, whose K argument must a scalar.  In the case where more than one argument is an array, then all arguments must have the same shape, and the bitwise operator is applied to each of the elements of the argument individually.  If at least one argument is a scalar and one an array, then the scalar argument is duplicated.  Therefore

     bitget (100, 8:-1:1)

is the same as

     bitget (100 * ones (1, 8), 8:-1:1)

It should be noted that all values passed to the bit manipulation functions of Octave are treated as integers.  Therefore, even though the example for bitset above passes the floating point value 10, it is treated as the bits [1, 0, 1, 0] rather than the bits of the native floating point format representation of 10.

As the maximum value that can be represented by a number is important for bit manipulation, particularly when forming masks, Octave supplies the function bitmax.

(bitmax)

This is the double precision version of the function intmax, previously discussed.

Octave also includes the basic bitwise 'and', 'or', and 'exclusive or' operators.

(bitand)

(bitor)

(bitxor)

The bitwise 'not' operator is a unary operator that performs a logical negation of each of the bits of the value.  For this to make sense, the mask against which the value is negated must be defined.  Octave's bitwise 'not' operator is bitcmp.

(bitcmp)

Octave also includes the ability to left-shift and right-shift values bitwise.

(bitshift)

Bits that are shifted out of either end of the value are lost.  Octave also uses arithmetic shifts, where the sign bit of the value is kept during a right shift.  For example:

     bitshift (-10, -1)
     => -5
     bitshift (int8 (-1), -1)
     => -1

Note that bitshift (int8 (-1), -1) is -1 since the bit representation of -1 in the int8 data type is [1, 1, 1, 1, 1, 1, 1, 1].

Logical Values
==============

Octave has built-in support for logical values, i.e., variables that are either true or false.  When comparing two variables, the result will be a logical value whose value depends on whether or not the comparison is true.

The basic logical operations are &, |, and !, which correspond to ``Logical And'', ``Logical Or'', and ``Logical Negation''.  These operations all follow the usual rules of logic.

It is also possible to use logical values as part of standard numerical calculations.  In this case true is converted to 1, and false to 0, both represented using double precision floating point numbers.  So, the result of true*22 - false/6 is 22.

Logical values can also be used to index matrices and cell arrays. When indexing with a logical array the result will be a vector containing the values corresponding to true parts of the logical array. The following example illustrates this.

     data = [ 1, 2; 3, 4 ];
     idx = (data <= 2);
     data(idx)
          => ans = [ 1; 2 ]

Instead of creating the idx array it is possible to replace data(idx) with data( data <= 2 ) in the above code.

Logical values can also be constructed by casting numeric objects to logical values, or by using the true or false functions.

(logical)

(true)

(false)

Promotion and Demotion of Data Types
====================================

Many operators and functions can work with mixed data types.  For example,

     uint8 (1) + 1
         => 2

where the above operator works with an 8-bit integer and a double precision value and returns an 8-bit integer value.  Note that the type is demoted to an 8-bit integer, rather than promoted to a double precision value as might be expected.  The reason is that if Octave promoted values in expressions like the above with all numerical constants would need to be explicitly cast to the appropriate data type like

     uint8 (1) + uint8 (1)
         => 2

which becomes difficult for the user to apply uniformly and might allow hard to find bugs to be introduced.  The same applies to single precision values where a mixed operation such as

     single (1) + 1
         => 2

returns a single precision value.  The mixed operations that are valid and their returned data types are

  Mixed Operation   Result
  double OP single   single
  double OP integer   integer
  double OP char   double
  double OP logical   double
  single OP integer   integer
  single OP char   single
  single OP logical   single

The same logic applies to functions with mixed arguments such as

     min (single (1), 0)
        => 0

where the returned value is single precision.

In the case of mixed type indexed assignments, the type is not changed.  For example,

     x = ones (2, 2);
     x(1, 1) = single (2)
        => x = 2   1
               1   1

where x remains of the double precision type.

Predicates for Numeric Objects
==============================

Since the type of a variable may change during the execution of a program, it can be necessary to do type checking at run-time.  Doing this also allows you to change the behavior of a function depending on the type of the input.  As an example, this naive implementation of abs returns the absolute value of the input if it is a real number, and the length of the input if it is a complex number.

     function a = abs (x)
       if (isreal (x))
         a = sign (x) .* x;
       elseif (iscomplex (x))
         a = sqrt (real(x).^2 + imag(x).^2);
       endif
     endfunction

The following functions are available for determining the type of a variable.

(isnumeric)

(isfloat)

(isreal)

(iscomplex)

(ismatrix)

(isvector)

(isrow)

(iscolumn)

(isscalar)

(issquare)

(issymmetric)

(ishermitian)

(isdefinite)

(islogical)

(isprime)

If instead of knowing properties of variables, you wish to know which variables are defined and to gather other information about the workspace itself, see Status of Variables.