Using the C++ Math Library    

Logical Values

In MATLAB, a logical value is either a logical scalar or an array of logical values. You create a logical array by calling the logical() function or by using a relational operator to compare two arrays. In C++, logical values are always scalars. A 1-by-1 mwArray object can be cast to a scalar. When an array object appears where a logical value is expected, C++ automatically attempts to cast the array to a scalar. This casting operation fails (raises an exception) if the array is not 1-by-1.

When a relational operation between arrays appears where a scalar Boolean value is required, you must use the MATLAB C++ Math Library function tobool() to reduce the result of the operation to a scalar Boolean. tobool() reduces any real or complex array to a Boolean true or false result. If you pass tobool() an empty array, it returns false.

For example, to test if every element in an array A is nonzero, write:

if and while statements in C++ require you to use these functions. Because the relational operators (<, >, <=, >=, == and !=) each return an array of logical values in both MATLAB and C++, it is necessary, when using the result of one of these operators in an if or while statement, to wrap it with a call to tobool().

There is one exception to this rule: if an array is a scalar, tobool() is unnecessary, since the compiler will attempt to convert the array, by default, to a double. However, if the array is not a scalar, this conversion fails at runtime and throws an exception.


 Control Structure Name Conflicts with Standard C Library Functions