I have a matrix in 2x2
a ={{x, y}, {z, u}}
I want to expand this matrix 3x3
b ={{x, y, y}, {z, u, x}, {z, x, u}}
4x4
c ={{x, y, y, y}, {z, u, x, x}, {z, x, u, x}, {z, x, x, u}}
5x5
d ={{x, y, y, y, y}, {z, u, x, x, x}, {z, x, u, x, x}, {z, x, x, u, x}, {z, x, x, x, u}}
and soon...
Basically, I am adding a row and column each time. How to do this automatically, without writing each time?
Edit:
Now consider x, y,z and u are also 2x2 matrices.
Lets
x={{0,1},{1,0}}, y={{1,1},{1,0}}, z={{1,0},{1,1}}
and
u = {{p,q},{r,s}}.
How I can get a,b,c and d (defined above) in this case?
Answer
Final answer:
f3[n_] := Module[{m, x, y, z, u},
m = Normal@SparseArray[Band[{2, 2}] -> u, {n, n}, x];
m[[2 ;;, 1]] = z;
m[[1, 2 ;;]] = y;
x = {{0, 1}, {1, 0}};
y = {{1, 1}, {1, 0}};
z = {{1, 0}, {1, 1}};
u = {{p, q}, {r, s}};
ArrayFlatten[m]
]
f3[6] // MatrixForm

First answer,
For example:
f[2] = {{x, y}, {z, u}};
f[n_] := f[n] = ReplacePart[ArrayPad[f[n - 1], {{0, 1}, {0, 1}}, x],
{{-1, -1} -> u, {1, -1} -> y, {-1, 1} -> z}]
You may be interested in explanation of f[n_]:=f[n]=... construct
I chose this way becasue you've said you are expanding an array each time adding one row and column. So this is quite nautral approach in such case.
If you are not interested in mediate results, but only in f[2] and f[15] for example, belisarius solution is a way to go.
First response to edit:
second code, more safe approach:
f2[n_] := Module[{m, x, y, z, u},
m = Nest[ ReplacePart[ ArrayPad[#, {{0, 1}, {0, 1}}, x],
{{-1, -1} -> u, {1, -1} -> y, {-1, 1} -> z}] &,
{{x, y}, {z, u}}, n - 2];
x = {{0, 1}, {1, 0}};
y = {{1, 1}, {1, 0}};
z = {{1, 0}, {1, 1}};
u = {{p, q}, {r, s}};
ArrayFlatten[m]
]
f2[5] // MatrixForm

Comments
Post a Comment