如何在 python 中追加多个矩阵
How to append multiple matrices in python
我已阅读以下相关讨论
What's the simplest way to extend a numpy array in 2 dimensions?
但是,如果我想扩展多个矩阵,例如
A = np.matrix([[1,2],[3,4]])
B = np.matrix([[3,4],[5,6]])
C = np.matrix([[7,8],[5,6]])
F = np.append(A,[[B]],0)
然而,python 表示
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 4 dimension(s)
我想把 B 放在矩阵 A 的“下面”,把 C 放在矩阵 B 的“下面”。
所以,F应该是一个6X2的矩阵。
如何做到这一点?谢谢!
我相信 np.concatenate 应该可以解决问题
A = np.matrix([[1,2],[3,4]])
B = np.matrix([[3,4],[5,6]])
C = np.matrix([[7,8],[5,6]])
ABC = np.concatenate([A,B,C],axis = 0) # axis 0 stacks it one above the other
print("Shape : ",ABC.shape)
print(ABC)
输出:
Shape : (6, 2)
matrix(
[[1, 2],
[3, 4],
[3, 4],
[5, 6],
[7, 8],
[5, 6]])
尝试使用 numpy.concatenate (https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html):
A = np.matrix([[1,2],[3,4]])
B = np.matrix([[3,4],[5,6]])
C = np.matrix([[7,8],[5,6]])
# F = np.append(A,[[B]],0)
F = np.concatenate((A, B, C), axis=1)
将轴参数更改为 0 以组合矩阵 'vertically':
print(np.concatenate((A, B, C), axis=1))
[[1 2 3 4 7 8]
[3 4 5 6 5 6]]
print(np.concatenate((A, B, C), axis=0))
[[1 2]
[3 4]
[3 4]
[5 6]
[7 8]
[5 6]]
我已阅读以下相关讨论 What's the simplest way to extend a numpy array in 2 dimensions?
但是,如果我想扩展多个矩阵,例如
A = np.matrix([[1,2],[3,4]])
B = np.matrix([[3,4],[5,6]])
C = np.matrix([[7,8],[5,6]])
F = np.append(A,[[B]],0)
然而,python 表示
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has 4 dimension(s)
我想把 B 放在矩阵 A 的“下面”,把 C 放在矩阵 B 的“下面”。
所以,F应该是一个6X2的矩阵。
如何做到这一点?谢谢!
我相信 np.concatenate 应该可以解决问题
A = np.matrix([[1,2],[3,4]])
B = np.matrix([[3,4],[5,6]])
C = np.matrix([[7,8],[5,6]])
ABC = np.concatenate([A,B,C],axis = 0) # axis 0 stacks it one above the other
print("Shape : ",ABC.shape)
print(ABC)
输出:
Shape : (6, 2)
matrix(
[[1, 2],
[3, 4],
[3, 4],
[5, 6],
[7, 8],
[5, 6]])
尝试使用 numpy.concatenate (https://numpy.org/doc/stable/reference/generated/numpy.concatenate.html):
A = np.matrix([[1,2],[3,4]])
B = np.matrix([[3,4],[5,6]])
C = np.matrix([[7,8],[5,6]])
# F = np.append(A,[[B]],0)
F = np.concatenate((A, B, C), axis=1)
将轴参数更改为 0 以组合矩阵 'vertically':
print(np.concatenate((A, B, C), axis=1))
[[1 2 3 4 7 8]
[3 4 5 6 5 6]]
print(np.concatenate((A, B, C), axis=0))
[[1 2]
[3 4]
[3 4]
[5 6]
[7 8]
[5 6]]