计算每个元素与python

时间:2018-08-08 08:10:31

标签: python numpy

我正在计算numpy数组中每个元素的差。我的代码是

import numpy as np

M = 10

x = np.random.uniform(0,1,M)

y = np.array([x])

# Calculate the difference

z = np.array(y[:,None]-y)

运行代码时,我得到[[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]]。我没有得到10 x 10的阵列。

我哪里出错了?

2 个答案:

答案 0 :(得分:2)

您应该阅读numpy的broadcasting rules

y.T - x

另一种方式:

np.subtract.outer(x, x)

答案 1 :(得分:0)

由于M的值为10,因此无法得到10 x 10的数组。

    M = (10,10)