numpy广播
最近有一个小需求,给定
a = [0,1,2]
M = [[1,1,],[1,1]]
求得
T = [ [[0,0],
[0,0]],
[[1,1],
[1,1]],
[[2,2],
[2,2]] ]
经过尝试,终于采用如下代码成功
((a.reshape(3,1)) * M.reshape(1,4)).reshape(3,2,2)
显示为
>>> ((a.reshape(3,1)) * M.reshape(1,4)).reshape(3,2,2)
array([[[0, 0],
[0, 0]],
[[1, 1],
[1, 1]],
[[2, 2],
[2, 2]]])
说明:a.reshape(3,1)将a从向量升级成矩阵,所以上面也可以用
>>> a.reshape(3,1).dot(M.reshape(1,4)).reshape(3,2,2)
array([[[0, 0],
[0, 0]],
[[1, 1],
[1, 1]],
[[2, 2],
[2, 2]]])