这是我的代码。我希望它返回的是一个矩阵数组
[[1,1],[1,1]],[[2,4],[8,16]],[[3,9],[27,81]]
我知道我可能可以使用 for 循环并循环遍历我的向量 k 来做到这一点,但我想知道是否有一种我缺少的简单方法。谢谢!
from numpy import *
import numpy as np
k=np.arange(1,4,1)
print k
def exam(p):
return np.array([[p,p**2],[p**3,p**4]])
print exam(k)
输出:
[1 2 3]
[[[ 1 2 3]
[ 1 4 9]]
[[ 1 8 27]
[ 1 16 81]]]
最佳答案
关键是玩弄形状和广播。
b = np.arange(1,4) # the base
e = np.arange(1,5) # the exponent
b[:,np.newaxis] ** e
=>
array([[ 1, 1, 1, 1],
[ 2, 4, 8, 16],
[ 3, 9, 27, 81]])
(b[:,None] ** e).reshape(-1,2,2)
=>
array([[[ 1, 1],
[ 1, 1]],
[[ 2, 4],
[ 8, 16]],
[[ 3, 9],
[27, 81]]])
如果您必须将输出作为矩阵列表,请执行以下操作:
m = (b[:,None] ** e).reshape(-1,2,2)
[ np.mat(a) for a in m ]
=>
[matrix([[1, 1],
[1, 1]]),
matrix([[ 2, 4],
[ 8, 16]]),
matrix([[ 3, 9],
[27, 81]])]
关于python - 矩阵数组,使用 Python 中数组中的值构建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20738104/