您可以通过堆叠单位矩阵乘以您要使用的值来完成构建特殊矩阵的技巧。
我将使用 3x3 矩阵作为示例,但对于任意矩阵的想法是相同的:
假设我们要乘以矩阵:
A = np.array([
[1,0,1],
[0,1,0],
[0,0,1]
])
按 [2、3 和 5]。没有循环。
我们可以构建一个包含身份的特殊矩阵来做到这一点:
[ 2 * np.eye(3), 3 * np.eye(3), 5 * np.eye(3)]
[ 0 0 2 ] [ 0 0 3] [ 0 0 5 ]
[ 0 2 0 ] [ 0 3 0] [ 0 5 0 ]
[ 2 0 0 ] [ 3 0 0] [ 5 0 0 ]
我们可以通过列表推导来做到这一点:
multiply_values = [2,3,5]
special_matrix = np.concatenate( [ x * eye(3) for x in multiply_values ], axis=1)
# special_matrix is:
# array([[2., 0., 0., 3., 0., 0., 5., 0., 0.],
# [0., 2., 0., 0., 3., 0., 0., 5., 0.],
# [0., 0., 2., 0., 0., 3., 0., 0., 5.]])
现在我们可以一步将矩阵相乘:
result = np.dot( , special_matrix)
# result is
array([[2., 0., 0., 3., 0., 0., 5., 0., 0.],
[0., 2., 0., 0., 3., 0., 0., 5., 0.],
[0., 0., 2., 0., 0., 3., 0., 0., 5.]])
可能这个大而宽的矩阵不是我们需要的。
我们可以得到切片结果产品的部分结果:
result[:,0:3]
# array([[2., 0., 2.],
# [0., 2., 0.],
# [0., 0., 2.]])
我们可以用另一种理解来处理切片:
[ special_matrix[:,x:x+3] for x in [0,3,6] ]
# or in a more general way
[ special_matrix[:,x:x+A.shape[0]] for x in list(range(0,A.shape[0]**2,A.shape[0] ]