I have a matrix of some values between 0 and 1:

values = RandomReal[{0, 1}, {dx, dy}]

Now I want to "binarize them", ie compare them to some random probabilities - if greater, return 1, else, return 0. Here are some ways to do this:

Boole[MapThread[#1 > #2 &, {values, RandomReal[{0, 1}, {dx, dy}]}, 2]]


Table[RandomVariate[BinomialDistribution[1, values[[i, j]]]], {i, 1, dx}, {j, 1, dy}]

What are some others, and what is the fastest?


The fastest is likely UnitStep[a-b] where a is your matrix, and b is either a scalar to compare to or another matrix of the same dimensions. This will give 1s where a >= b.

My BoolEval package allows for nicer notation, especially when the operation you want is not exactly >=.

BoolEval[a >= b]
  • $\begingroup$ Just in case, Sign seems to be about as fast as UnitStep, but returns values in $\{-1,1\}$ instead of $\{0,1\}$. $\endgroup$ – anderstood Jan 15 '18 at 21:02
  • $\begingroup$ Wow, that is fast! Thanks $\endgroup$ – smörkex Jan 15 '18 at 21:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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