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?
nma
(Nasser M. Abbasi)
September 6, 2013, 5:18am
2
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} *)
arnoudb
(Arnoud Buzing)
September 6, 2013, 1:15pm
4
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
iliang
(Ilian Gachevski)
September 6, 2013, 2:49pm
5
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}