# How to replace the selected value in matrix with a specific digit?

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]

• Maybe you just need mat = RandomInteger[1, {6, 3}] – eldo Jan 3 '16 at 19:44

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.

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