6
$\begingroup$

If there is a submatrix, let's call $P$:

$P=\begin{pmatrix} 1 & 1 \\ 1 & 1 \end{pmatrix}$

And I want to have $n$, let's say $n=2$, such submatrices placed on the diagonal. The result is expected to look like:

$Q=\begin{pmatrix} 1 & 1 & 0 & 0 \\ 1 & 1 & 0 & 0 \\ 0 & 0 & 1 & 1 \\ 0 & 0 & 1 & 1 \end{pmatrix}$

How do I write the code in Mathematica?

$\endgroup$
3
  • 3
    $\begingroup$ This seems to be a special case of this question: How to form a block-diagonal Matrix from a list of matrices? $\endgroup$
    – Michael E2
    Commented Sep 8, 2014 at 18:22
  • $\begingroup$ I noticed that thread. Well, it didn't say how to do that $n$ times. $\endgroup$
    – user33869
    Commented Sep 8, 2014 at 18:48
  • 1
    $\begingroup$ Mainly I was just linking the question -- see "Linked" in column on the right -- so that others might easily find it. Some of the answers there are easily adapted (using ConstantArray[P, n] for the list of matrices), but special cases often also have special solutions. $\endgroup$
    – Michael E2
    Commented Sep 8, 2014 at 18:58

3 Answers 3

8
$\begingroup$
f1 = KroneckerProduct[IdentityMatrix[#], #2]& 
f2 = SparseArray[{Band[{1, 1}, # Dimensions@#2] -> {#2}}] &
f3 = SparseArray[{Band[{1, 1}] -> ConstantArray[#2, #]}] &
f4 = ArrayFlatten[IdentityMatrix[#] /. 1 -> #2 ] &

p = Table[1, {2}, {2}];
f1[3, p]
f2[3, p] // Normal
f3[3, p] // Normal
f4[3, p]

all give

(* {{1,1,0,0,0,0},{1,1,0,0,0,0},
    {0,0,1,1,0,0},{0,0,1,1,0,0},
    {0,0,0,0,1,1},{0,0,0,0,1,1}} *)
$\endgroup$
2
  • $\begingroup$ I posted basically the same thing here, but unfortunately the thread got closed. $\endgroup$
    – Jens
    Commented Sep 8, 2014 at 18:18
  • $\begingroup$ @Jens, yes these are special cases of the answers in that Q/a and in the one linked there. $\endgroup$
    – kglr
    Commented Sep 8, 2014 at 18:58
5
$\begingroup$
mat[p_, n_] := ArrayFlatten[DiagonalMatrix[Array[1 &, n]] /. {1 -> p, 0 -> 0 p}]
p = {{1, 2}, {3, 1}};
mat[p, 3] // MatrixPlot

Mathematica graphics

$\endgroup$
2
  • 2
    $\begingroup$ I'm slowly deleting my nearly identical answer now sobbing softly. $\endgroup$
    – kale
    Commented Sep 8, 2014 at 15:40
  • $\begingroup$ @kale Soooo sorry :) $\endgroup$ Commented Sep 8, 2014 at 15:42
4
$\begingroup$

Also useful here would be the Outer product:

p = ConstantArray[1, {2, 2}];
ArrayFlatten[Outer[Times, IdentityMatrix[2], p]]

which gives the desired output (displayed using MatrixForm)

enter image description here

$\endgroup$

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.