多维数组的递归矩阵元素加法

问题描述 投票:0回答:1

如果矩阵的大小是(3,4,4);

new_matrix =矩阵[0] +矩阵[1] +矩阵[2]

我如何对矩阵的每个元素进行逐元素加法。'

示例:

矩阵= np.array([[[1,2],[3,4]],[[4,5],[6,7]],[[8,9],[10,11]] ])

new_matrix = np.zeros(shape =(2,2))

for i在range(matrix.shape [0]):new_matrix + =矩阵[i]

print(new_matrix)

答案:[[13,16],[19,22]]

问题:没有for循环,我该怎么办?

python numpy addition
1个回答
0
投票

您可以使用numpy中提供的np.sum功能。您可以指定要执行加法的轴,否则它将给出矩阵中所有元素的总和。

例如,

matrix = np.array([[[1, 2], [3, 4]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]])
print(np.sum(matrix,axis=0))

输出为

[[13 16]
 [19 22]]

这是np.sum文档的链接:np.sum

© www.soinside.com 2019 - 2024. All rights reserved.