1
$\begingroup$

I would like to define a function that constructs a matrix consisting of different parts (submatrices). I.e. something like

 Matrix[k_,l_,n_]:=ReplacePart[ConstantArray[0,{n,n}], {1;;3,1;;n}->f[k] and {n-1;;n,n-1;;n}->g[l]]

where f[k] returns a 3xn matrix and g[l] returns a 2x2 matrix. The above code doesn't work (obviously) but I am looking for something like this. Replace does work only with a single element but not with a submatrix.

$\endgroup$

2 Answers 2

2
$\begingroup$

Update: A cleaner version using SparseArray and Band:

ClearAll[matrix3]
matrix3[k_, l_, n_] := SparseArray[{Band[{1, 1}] -> f[k, n], 
    Band[{n - l + 1, n - l + 1}] -> g[l]}, {n, n}];

matrix3[3, 4, 10] // MatrixForm

Mathematica graphics

Original post: You can use Set to change blocks of Parts:

ClearAll[g, f, matrix]
f[k_, n_] := RandomChoice[CharacterRange["a", "z"], {k, n}];
g[l_] := RandomChoice[{a, b, c, d, e}, {l, l}];

matrix[k_, l_, n_] :=  Module[{ca = ConstantArray[0, {n, n}]}, ca[[;; k, ;; n]] = f[k, n]; 
  ca[[n - l + 1 ;;, n - l + 1 ;;]] = g[l]; ca]

matrix[4, 3, 10] // MatrixForm

Mathematica graphics

If you have to use ReplacePart:

matrix2[k_, l_, n_] := Module[{ca = ConstantArray[0, {n, n}]}, 
  ReplacePart[ca, Join[Thread[ Tuples[Range /@ {k, n}] -> (Join @@ f[k, n])], 
    Thread[ Tuples[Range[n - l + 1, n], 2] -> (Join @@ g[l])]]]]

matrix2[3, 4, 10] // MatrixForm

Mathematica graphics

$\endgroup$
2
$\begingroup$

In:

Clear[n, x, y];
matrix[k_, l_, n_] := Module[{replace},
   replace[x_, y_] := Module[{},
     Which[
      {x, y} \[Element] Rectangle[{1, 1}, {3, n}], f[k],
      {x, y} \[Element] Rectangle[{n - 1, n - 1}, {n, n}], g[l],
      True, 0]];
   Array[replace, {n, n}]];

matrix[k, l, 6] // MatrixForm

Out:

Mathematica graphics

$\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.