1
$\begingroup$

I want to replace the selected values through "RandomChoice" by 1 and all other values in matrix with 0. I want output in binary form matirx.

mat = Table[Subscript[m, i, j], {i, 6}, {j, 3}];
    mat // MatrixForm
    n = 18*0.5;
    k = RandomChoice[{mat[[1, 1]], mat[[1, 2]], mat[[1, 3]], mat[[2, 1]], 
       mat[[2, 2]], mat[[2, 3]], mat[[3, 1]], mat[[3, 2]], mat[[3, 3]], 
       mat[[4, 1]], mat[[4, 2]], mat[[4, 3]], mat[[5, 1]], mat[[5, 2]], 
       mat[[5, 3]], mat[[6, 1]], mat[[6, 2]], mat[[6, 3]]}, n]
$\endgroup$
  • 2
    $\begingroup$ Maybe you just need mat = RandomInteger[1, {6, 3}] $\endgroup$ – eldo Jan 3 '16 at 19:44
1
$\begingroup$

I would go for making the binary matrix directly.

randBinary[rows_Integer, cols_Integer, ones_Integer] :=
  Module[{i, v0, v1},
    i = rows cols; 
    v0 = ConstantArray[0, i];
    v1 = List /@ RandomSample[Range[i], ones];
    Partition[ReplacePart[v0, v1 -> 1], cols]]

SeedRandom[42];
Column[{randBinary[6, 3, 9], randBinary[3, 2, 3]}]
{{1, 1, 0}, {0, 1, 0}, {1, 1, 1}, {0, 0, 0}, {0, 1, 1}, {0, 0, 1}}
{{1, 0}, {0, 1}, {0, 1}}

Note that what you asking for requires RandomSample not RandomChoice; you don't want a position to be selected more than once.

$\endgroup$
1
$\begingroup$

As I understand your goal, you want exactly 50% 1s and the rest 0s. (By implication, either r or k is even, below.)

r = 6; k = 3;
RandomSample@Flatten@ConstantArray[{1, 0}, r*k/2]~Partition~k
$\endgroup$

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.