Next: , Previous: , Up: Numeric Data Types   [Contents][Index]


4.6 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 (x)

Convert the numeric object x to logical type.

Any nonzero values will be converted to true (1) while zero values will be converted to false (0). The non-numeric value NaN cannot be converted and will produce an error.

Compatibility Note: Octave accepts complex values as input, whereas MATLAB issues an error.

See also: double, single, char.

: val = true (x)
: val = true (n, m)
: val = true (n, m, k, …)
: val = true (…, "like", var))

Return a matrix or N-dimensional array whose elements are all logical 1.

If invoked with a single scalar integer argument, return a square matrix of the specified size.

If invoked with two or more scalar integer arguments, or a vector of integer values, return an array with given dimensions.

If a logical variable var is specified after "like", the output val will have the same sparsity as var.

See also: false.

: val = false (x)
: val = false (n, m)
: val = false (n, m, k, …)
: val = false (…, "like", var))

Return a matrix or N-dimensional array whose elements are all logical 0.

If invoked with a single scalar integer argument, return a square matrix of the specified size.

If invoked with two or more scalar integer arguments, or a vector of integer values, return an array with given dimensions.

If a logical variable var is specified after "like", the output val will have the same sparsity as var.

See also: true.


Next: Automatic Conversion of Data Types, Previous: Bit Manipulations, Up: Numeric Data Types   [Contents][Index]