[英]How to create a matrix from several other matrices?
I have a problem with joining several matrices.我在加入几个矩阵时遇到问题。 Say I have four matrices A,B,C,D.
假设我有四个矩阵 A、B、C、D。 And I want to join them in a way to obtain a new one
我想以某种方式加入他们以获得新的
M = A B
C D
How can I do this using python numpy?如何使用 python numpy 执行此操作?
Considering all have same dimension, here's an example:考虑到所有尺寸都相同,这里有一个例子:
>>> A = np.arange(4).reshape(2,2)
>>> B, C, D = A*2, (A+1), (A+2)
>>> M = np.array([[A,B],[C,D]])
>>> M
array([[[[0, 1],
[2, 3]],
[[0, 2],
[4, 6]]],
[[[1, 2],
[3, 4]],
[[2, 3],
[4, 5]]]])
Or if you want something like this:或者如果你想要这样的东西:
>>> M = np.concatenate([np.concatenate([A,B],axis = 1),np.concatenate([C,D],axis = 1)],axis = 0)
>>> M
array([[0, 1, 0, 2],
[2, 3, 4, 6],
[1, 2, 2, 3],
[3, 4, 4, 5]])
Using NumPy's hstack
and vstack
functions, you can generate M
from any A
, B
, C
, D
as long as each two number of rows and/or number of columns match.使用 NumPy 的
hstack
和vstack
函数,您可以从任何A
、 B
、 C
、 D
生成M
,只要每两个行数和/或列数匹配。 See the following example:请参见以下示例:
import numpy as np
A = np.random.rand(3, 2) # (3 x 2)
B = np.random.rand(3, 4) # (3 x 4)
C = np.random.rand(4, 3) # (4 x 3)
D = np.random.rand(4, 3) # (4 x 3)
print(A, '\n')
print(B, '\n')
print(C, '\n')
print(D, '\n')
M = np.vstack((np.hstack((A, B)), np.hstack((C, D))))
# (3 x 6) (4 x 6)
# (7 x 6)
print(M)
Output: Output:
[[0.60220154 0.77067838]
[0.7623169 0.54727146]
[0.20570341 0.56939493]]
[[0.322524 0.35260186 0.6581785 0.55662823]
[0.32034862 0.68664386 0.96432518 0.03410233]
[0.72779584 0.6705618 0.66460412 0.104223 ]]
[[0.20194483 0.49971436 0.50618483]
[0.89040491 0.25118623 0.67831283]
[0.30631334 0.69515443 0.70941023]
[0.41324506 0.23127909 0.29241595]]
[[0.0015009 0.43205507 0.08500188]
[0.48506546 0.46448833 0.61393518]
[0.51163779 0.81914233 0.21293481]
[0.33713576 0.33953848 0.9909197 ]]
[[0.60220154 0.77067838 0.322524 0.35260186 0.6581785 0.55662823]
[0.7623169 0.54727146 0.32034862 0.68664386 0.96432518 0.03410233]
[0.20570341 0.56939493 0.72779584 0.6705618 0.66460412 0.104223 ]
[0.20194483 0.49971436 0.50618483 0.0015009 0.43205507 0.08500188]
[0.89040491 0.25118623 0.67831283 0.48506546 0.46448833 0.61393518]
[0.30631334 0.69515443 0.70941023 0.51163779 0.81914233 0.21293481]
[0.41324506 0.23127909 0.29241595 0.33713576 0.33953848 0.9909197 ]]
You can switch vstack
and hstack
, if the number of columns of A
/ C
and B
/ D
match, and the number of rows of these concatenations are equal.可以切换
vstack
和hstack
,如果A
/ C
和B
/ D
的列数匹配,并且这些连接的行数相等。
Hope that helps!希望有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.