Matrix Randomization

Is there a way to take a 20x20 array and replace 2 random parts of this array with a 2x2 matrix?

I've tried

rvalues = ConstantArray[r, {20, 20}];

to make the array, but dont know how to use ReplacePart[rvalues, RandomInteger]

Any advice would be appreciated

1 Answer

n = 6;
a = ConstantArray[0, {n, n}];
pos = RandomSample[1 ;; n, 2];
vals = RandomInteger[{1, 10}, {2, 2}];


Now you can either perform the replacement with ReplacePart

anew = ReplacePart[a, Thread[Tuples[pos, 2] -> Flatten[vals]]];
anew // MatrixForm


$$\left( \begin{array}{cccccc} 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 8 \\ 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 10 & 0 & 0 & 5 \\ \end{array} \right)$$

or in-place with Part

a[[pos, pos]] = vals;
a // MatrixForm


$$\left( \begin{array}{cccccc} 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 & 0 & 8 \\ 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 0 & 0 & 0 & 0 \\ 0 & 0 & 10 & 0 & 0 & 5 \\ \end{array} \right)$$

• Might want to use RandomSample[Range[n], 2] instead, to avoid repeats. Sep 24, 2018 at 23:10
• @CarlWoll Good point!. Thanks. Sep 24, 2018 at 23:23