Message Boards Message Boards

1
|
6924 Views
|
4 Replies
|
3 Total Likes
View groups...
Share
Share this post:

Logic AND in Matlab vs Mathematica?

Posted 12 years ago
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?
POSTED BY: feng wei
4 Replies
I am not sure if Matlab does a bitwise operation, it may be more similar to
In[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 with
In[4]:= BitAnd[{2, 3, 0}, {0, 4, 3}]

Out[4]= {0, 0, 0}
POSTED BY: Ilian Gachevski
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.html
http://reference.wolfram.com/mathematica/ref/BitOr.html
http://reference.wolfram.com/mathematica/ref/Replace.html
POSTED BY: Arnoud Buzing
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 BY: Nasser M. Abbasi
Posted 12 years ago
Thanks  to Nasser
POSTED BY: feng wei
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract