For those transitioning between Matlab/Octave and Python, the “logical not” tilde
~ operator of Matlab/Octave is NOT matched in Python.
In Python (on non-Numpy variables),
~ means unary complement.
~ operates on the bits of the byte underlying each non-Numpy Boolean (in Matlab/Octave, boolean is class
- Numpy does not allow the word
notfor Numpy arrays.
- safest way (if cumbersome) is to always use
- If you know you won’t have any Numpy arrays, you can use the word
- If you know you always have Numpy arrays, you can use
~, but it’s safer to use
notwill at least throw a
ValueErrorif you use it on a Numpy array, rather than silently giving the wrong value as
~will on non-Numpy arrays.
My operating practice is to use
logical_not() and avoid
~ to avoid silent failures.
|non-Numpy||unary complement |
|Numpy||logical not |
|Matlab||logical not |
This critically important distinction comes from the short int (byte) inherited by the Python