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.
- true (x)
- true (n, m)
- true (n, m, k, …)
-
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.
See also: false.
- false (x)
- false (n, m)
- false (n, m, k, …)
-
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.
See also: true.
© 1996–2020 John W. Eaton
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://octave.org/doc/v5.2.0/Logical-Values.html