线性数组python的平方数组

时间:2018-11-23 14:08:53

标签: python arrays numpy matrix vector

我想从线性向量B得到一个A的方阵B = A * transpose(A)A是一个numpy数组,而np.shape(A)返回(10,)。我希望B是一个(10,10)数组。我尝试了B = np.matmut(A, A[np.newaxis]),但收到错误消息:

shapes (10,) and (1,10) not aligned: 10 (dim 0) != 1 (dim 0)

3 个答案:

答案 0 :(得分:3)

您可以使用outer进行此操作:

import numpy as np
vector = np.arange(10)
np.outer(vector, vector)

答案 1 :(得分:2)

解决方案有点难看,但是它可以满足您的需求。

import numpy as np

vector = np.array([1,2,3,4,5,6,7,8,9,10],)
matrix = np.dot(vector[:,None],vector[None,:])
print(matrix)

您还可以执行以下操作:

import numpy as np

vector = np.array([1,2,3,4,5,6,7,8,9,10],)
matrix = vector*vector[:,None]
print(matrix)

问题出在以下事实:转置一维数组并没有您预期的效果。

答案 2 :(得分:0)

外部产品的变化

a = A.reshape(-1, 1) # make sure it's a column vector
B = a @ a.T