Reputation: 1999
Is it normal that Matlab returns a double as a result for a logical multiplication ?
A=[true false];
B=[false true];
class(A.*B)
output is
ans =
double
The best way I found is a cast : logical(A.*B)
, but I do not feel it is clean.
Upvotes: 1
Views: 514
Reputation: 23685
In many languages (including Matlab) the boolean type
(called logical
in Matlab) is not a numeric type, even if it has an underlying numeric type (just like every other type). It's underlying numeric type is nothing but a byte
(uint8
in Matlab) whose possible values are constrained to 0
and 1
.
In the majority of programming languages, when you try to perform arithmetic operations between booleans, the compiler throws an error telling you that it's not possible. Matlab, on the opposite, performs an implicit conversion of your logicals
to double
before proceeding with the calculations, and let you go on without errors:
A = [true false]; => A = [1 0];
B = [false true]; => A = [0 1];
ans = A .* B;
whos ans => double
That's why your result type is double
.
Actually, if you want to perform operations with logicals
, sticking to logical
return type... you have to use logical operators. For more details: https://mathworks.com/help/matlab/logical-operations.html
Actually, your result can be achieved staying in the logical
domain through:
res = A & B;
Upvotes: 2
Reputation: 1999
I found ! It is simply A&B
>> A&B
ans =
0 0
>> class(ans)
ans =
logical
Upvotes: 0