7
$\begingroup$

I would like to generate a matrix whose dimension is L^2 and whose entries can be only in a finite set but in random positions in the matrix.

such as

 M[b_]:=RandomReals[{0,b},{L,L}]

where b is an integer. However the latter gives random values in the range 0 to b, while I want only entries that can be only 0 or b....namely several b distributed randomly in the matrix and all the other elements 0.

Is this possible?

$\endgroup$

2 Answers 2

10
$\begingroup$

You need RandomChoice,

RandomChoice[{0, b}, {4, 3}]
(* {{0, 0, 0}, {0, b, 0}, {b, b, 0}, {0, 0, b}} *)
$\endgroup$
5
$\begingroup$

For the case with two elements 0 and b you can also use:

b RandomInteger[1, {4, 4}]

{{0, 0, b, 0}, {0, 0, b, b}, {b, b, 0, 0}, {0, b, 0, 0}}

$\endgroup$
2
  • $\begingroup$ Thank you so much! $\endgroup$
    – Galuoises
    Feb 5, 2018 at 19:26
  • $\begingroup$ @Galuoises, my pleasure. $\endgroup$
    – kglr
    Feb 5, 2018 at 19:32

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.