1
$\begingroup$

I have this program, which turns 1 and 0s to True or False.

randombool = RandomVariate[BernoulliDistribution[0.5], 10]
{1, 0, 1, 0, 0, 1, 1, 0, 0, 1}

TrueOrFalse[x_] := Switch[x, 1, True, 0, False]

Convert = Map[TrueOrFalse, randombool]
{True, False, True, False, False, True, True, False, False, True}

But when I do with 2 lists it stops working, for example:

randombool = RandomVariate[BernoulliDistribution[0.5], {2, 10}]
{{1, 0, 1, 1, 1, 1, 0, 1, 1, 1}, {1, 0, 0, 1, 0, 0, 1, 0, 0, 1}}

TrueOrFalse[x_] := Switch[x, 1, True, 0, False]

Convert = Map[TrueOrFalse, randombool]
{Switch[{1, 0, 1, 1, 1, 1, 0, 1, 1, 1},
1, True,
0, False], Switch[{1, 0, 0, 1, 0, 0, 1, 0, 0, 1},
1, True,
0, False]}

What am I doing wrong here? Thanks.

$\endgroup$
5
  • 1
    $\begingroup$ Use Map[TrueOrFalse, randombool, {2}], i.e. map at 2nd level. $\endgroup$
    – Alx
    Commented Apr 6, 2020 at 15:00
  • $\begingroup$ You can also use ReplaceAll[{0 -> False, 1 -> True}]. $\endgroup$
    – Szabolcs
    Commented Apr 6, 2020 at 15:01
  • 1
    $\begingroup$ Or SetAttribute[TrueOrFalse, Listable] and then TrueOrFalse[randombool]. $\endgroup$
    – Alx
    Commented Apr 6, 2020 at 15:05
  • $\begingroup$ Or Map[(1 == #) &, {{1, 0, 1, 1, 1, 1, 0, 1, 1, 1}, {1, 0, 0, 1, 0, 0, 1, 0, 0, 1}}, {-1}] $\endgroup$ Commented Apr 6, 2020 at 15:19
  • $\begingroup$ Thank you Alx, it worked. $\endgroup$
    – joao
    Commented Apr 6, 2020 at 17:11

1 Answer 1

4
$\begingroup$

Use OddQ instead of TrueOrFalse. It's the fast and easy inverse to Boole.

In[25]:= OddQ[{{1, 0, 1, 1, 1, 1, 0, 1, 1, 1}, {1, 0, 0, 1, 0, 0, 1, 
   0, 0, 1}}]

Out[25]= {{True, False, True, True, True, True, False, True, True, 
  True}, {True, False, False, True, False, False, True, False, False, 
  True}}

Some quick timings:

In[1]:= ints = RandomInteger[1, 10^6];

In[6]:= RepeatedTiming[v1 = OddQ[ints];]
Out[6]= {0.015, Null}

In[7]:= RepeatedTiming[v2 = ReplaceAll[ints, {0 -> False, 1 -> True}];]
Out[7]= {0.160, Null}

In[8]:= TrueOrFalse[x_] := Switch[x, 1, True, 0, False];

In[9]:= RepeatedTiming[v3 = TrueOrFalse /@ ints;]
Out[9]= {0.533, Null}

In[10]:= RepeatedTiming[v4 = Map[(1 == #) &, ints, {-1}];]
Out[10]= {0.319, Null}

In[11]:= v1 == v2 == v3 == v4
Out[11]= True
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.