2

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]
]
corey979
  • 23,947
  • 7
  • 58
  • 101
victorshade
  • 83
  • 1
  • 1
  • 3

3 Answers3

3

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}]
bill s
  • 68,936
  • 4
  • 101
  • 191
3
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

eldo
  • 67,911
  • 5
  • 60
  • 168
3

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".

C. E.
  • 70,533
  • 6
  • 140
  • 264