# Logic AND in Matlab vs Mathematica?

Posted 10 years ago
5963 Views
|
4 Replies
|
3 Total Likes
|
 In matlab, the function 'and' can realize that input: and([2,3,0],[0,0,3]) and the result is [0,0,0]. In other words, Logical AND between both constants can realize the result of 1 or 0. However, in Mathematica this result can not be realized as follows:And[[2, 3, 0], [0, 0, 3]] How to realize the same function as matlab by mathematic?
4 Replies
Sort By:
Posted 10 years ago
 I am not sure if Matlab does a bitwise operation, it may be more similar toIn[2]:= Unitize[{2, 3, 0}*{0, 0, 3}]Out[2]= {0, 0, 0}In[3]:= Unitize[{2, 3, 0}*{0, 4, 3}]Out[3]= {0, 1, 0}Compare the last one withIn[4]:= BitAnd[{2, 3, 0}, {0, 4, 3}]Out[4]= {0, 0, 0}
Posted 10 years ago
 There is a family of bitwise logic functions (BitAnd, BitOr, BitXor, etc) which automatically threads over lists:BitAnd[{1, 2, 0}, {0, 2, 3}] (* returns {0,2,0} *)To turn non-zero values into ones, you can use Replace:Replace[ BitAnd[{1, 2, 0}, {0, 2, 3}], Except[0] -> 1, {1}] (* returns {0,1,0} *)http://reference.wolfram.com/mathematica/ref/BitAnd.htmlhttp://reference.wolfram.com/mathematica/ref/BitOr.htmlhttp://reference.wolfram.com/mathematica/ref/Replace.html
Posted 10 years ago
 There might be a function for this in Mathematica allready, but I could not find it. But one can write one if needed. matlabAnd[lis_?(MatrixQ[#, NumericQ] && FreeQ[#, _Complex] &)] /; Length[lis] == 2 := Module[{data = lis},   data = Map[If[Not[Chop[#] == 0], True, False] &, data, {2}];   data = MapThread[And, data];   data = Map[If[TrueQ[#], 1, 0] &, data]   ];Then you can use it as:matlabAnd[{{2, 3, 0}, {0, 0, 3}}](* {0, 0, 0}*)matlabAnd[{{2, 3, 0}, {0, 4, 3}}](* {0, 1, 0}*)matlabAnd[{{2, 3, 0}, {1, 5, 3}}](* {1, 1, 0} *)
Posted 10 years ago
 Thanks  to Nasser