2
$\begingroup$

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

$\endgroup$

1 Answer 1

2
$\begingroup$
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)$$

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

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.