2
$\begingroup$

How can I make a function that creates a particular size 2D matrix that determines True or False if a random value between 0 and 1 is at or below a certain number? Below is what I have written but when I put in values all I get is a column of trues.

initializeGrid[rows_Integer, columns_Integer, value_] := 
  Module[{table, booleanTable},
  table = Table[RandomReal[], {r, rows}, {c, columns}];
  booleanTable = BooleanTable[x <= value, table];
  Return[booleanTable]
]
$\endgroup$
1

3 Answers 3

3
$\begingroup$
SeedRandom[123]
ran = RandomReal[1, {5, 5}];

PaddedForm[TableForm[ran], {3, 2}]

enter image description here

Replace all numbers below n with False or True otherwise

n = 0.6;
Unitize @ Threshold[ran, n] /. {1 :> True, 0 :> False} // TableForm

enter image description here

$\endgroup$
3
$\begingroup$

There are many ways to get a matrix of True and False:

Table[RandomReal[] < 0.2, {i, 10}, {j, 10}]

Change the 0.2 to your desired threshold and the 10 to your desired matrix size.

Or use RandomChoice to directly choose between True and False with a given probability:

RandomChoice[{0.8, 0.2} -> {True, False}, {10, 10}]
$\endgroup$
3
$\begingroup$

You can use the BoolEval package.

Needs["BoolEval`"]

matrix = RandomReal[1, {3, 3}]
(* Out: {{0.965037, 0.544295, 0.191919}, {0.270774, 0.582857, 
  0.261769}, {0.4165, 0.935575, 0.243333}} *)

BoolEval[matrix < 0.5]
{{0, 0, 1}, {1, 0, 1}, {1, 0, 1}}

You can of course replace zeros with False and ones with True (/. {0 -> False, 1 -> True}) but don't do it unless you really need it, because those values are not stored as efficiently internally. If you do that then the list will no longer be "packed".

$\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.