我正在尝试根据输入的数组计算矩阵。
我希望能够输入
a = [0,1,2]
在 python 中,想用 Numpy reshape 它,结果是数组在第 i 行和第 j 列的形式为 x_i^j,
举个例子 输入是:
a = [0,1,2]
输出应该是
[[1,0,0],
[1,1,1],
[1,2,4]]
我使用了下面的代码
xij = np.matrix([np.power(xi,j) for j in x for xi in x]).reshape(3,3)
[[ 1, 2, 3],
[ 1, 4, 9],
[ 1, 8, 27]]
我假设我对 Numpy 使用了错误的公式, 请你帮我解决这个问题。 提前致谢
最佳答案
您需要使用 range(len(a))
来获取指数和 for 循环的正确顺序
a = [0,1,2]
xij = np.matrix([np.power(xi,j) for xi in a for j in range(len(a))]).reshape(3,3)
# matrix([[1, 0, 0],
# [1, 1, 1],
# [1, 2, 4]])
关于python - 我如何在 Numpy 的矩阵中计算 xi^j,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55435510/