Reputation: 479
I have four mxn matrices. From those matrices I want to create a mxn matrix of matrices such that each element of new matrix would be a 2x2 matrix taking respective elements from each matrix. So far I can think of stacking all four matrices and then reshape each element along z axis and replace it. I believe there is more elegant solution to this. Sample input:
$$
\begin{bmatrix}
A_{11} & A_{12}\\
A_{21} & A_{22}
\end{bmatrix}
,
\begin{bmatrix}
B_{11} & B_{12}\\
B_{21} & B_{22}
\end{bmatrix}
,
\begin{bmatrix}
C_{11} & C_{12}\\
C_{21} & C_{22}
\end{bmatrix}
,
\begin{bmatrix}
D_{11} & D_{12}\\
D_{21} & D_{22}
\end{bmatrix}
$$
Expected output:
$$
\begin{bmatrix}
\begin{bmatrix}
A_{11} & B_{11}\\
C_{11} & D_{11}
\end{bmatrix} & \begin{bmatrix}
A_{12} & B_{12}\\
C_{12} & D_{12}
\end{bmatrix}\\
\begin{bmatrix}
A_{21} & B_{21}\\
C_{21} & D_{21}
\end{bmatrix} & \begin{bmatrix}
A_{22} & B_{12}\\
C_{22} & D_{22}
\end{bmatrix}
\end{bmatrix
$$
Upvotes: 1
Views: 579
Reputation: 231325
A sample creating function:
In [510]: def foo(astr,m,n):
...: alist = [astr+'%d%d'%(i,j) for i in range(m) for j in range(n)]
...: return np.array(alist).reshape(m,n)
In [511]: foo('A',2,2)
Out[511]:
array([['A00', 'A01'],
['A10', 'A11']], dtype='<U3')
A list of 4 such arrays:
In [512]: alist = [foo('A',2,2),foo('B',2,2),foo('C',2,2),foo('D',2,2)]
Various ways of stacking:
In [513]: np.stack(alist)
Out[513]:
array([[['A00', 'A01'],
['A10', 'A11']],
[['B00', 'B01'],
['B10', 'B11']],
[['C00', 'C01'],
['C10', 'C11']],
[['D00', 'D01'],
['D10', 'D11']]], dtype='<U3')
In [514]: np.stack(alist,2)
Out[514]:
array([[['A00', 'B00', 'C00', 'D00'],
['A01', 'B01', 'C01', 'D01']],
[['A10', 'B10', 'C10', 'D10'],
['A11', 'B11', 'C11', 'D11']]], dtype='<U3')
In [515]: _.shape
Out[515]: (2, 2, 4)
This can be reshaped in various ways:
In [516]: __.reshape(2,2,2,2)
Out[516]:
array([[[['A00', 'B00'],
['C00', 'D00']],
[['A01', 'B01'],
['C01', 'D01']]],
[[['A10', 'B10'],
['C10', 'D10']],
[['A11', 'B11'],
['C11', 'D11']]]], dtype='<U3')
In [517]: _.reshape(4,2,2)
Out[517]:
array([[['A00', 'B00'],
['C00', 'D00']],
[['A01', 'B01'],
['C01', 'D01']],
[['A10', 'B10'],
['C10', 'D10']],
[['A11', 'B11'],
['C11', 'D11']]], dtype='<U3')
Instead different axis, you can create one and transpose the axes to your heart's content.
Upvotes: 1
Reputation: 345
Since all have mxn elements, make mxn iterations and at each iteration, build a 2x2 matrix from each element of the 4 matrices and then add the list to your final mxn matrix.
matrix1 = [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
matrix2 = [[2, 2, 2, 2], [2, 2, 2, 2], [2, 2, 2, 2]]
matrix3 = [[3, 3, 3, 3], [3, 3, 3, 3], [3, 3, 3, 3]]
matrix4 = [[4, 4, 4, 4], [4, 4, 4, 4], [4, 4, 4, 4]]
matrixFinal = []
for i in range(len(matrix1)):
matrixFinal.append([])
for j in range(len(matrix1[i])):
matrixFinal[i].append ([[matrix1[i][j], matrix2[i][j]], [matrix3[i][j], matrix4[i][j]]])
print(matrixFinal)
Upvotes: 0