如何使用Numpy找到给定矩阵的所有元素的和?
在这个程序中,我们将使用numpy库中的sum()函数将所有numpy矩阵的项相加。 首先,我们将创建一个随机的numpy矩阵,然后,我们将获取所有元素的总和。
阅读更多:Python 教程
算法
步骤1:导入numpy库。
步骤2:使用random()函数创建一个随机的m×n矩阵。
步骤3:使用sum()函数获取矩阵中所有元素的总和。
示例代码
import numpy as np
matrix = np.random.rand(3,3)
print("The numpy matrix is: \n",matrix)
print("\nThe sum of the matrix is: ", np.sum(matrix))
输出
The numpy matrix is:
[[0.66411969 0.43672579 0.48448593]
[0.76110384 0.35869136 0.51509622]
[0.22408857 0.17984855 0.33566272]]
The sum of the matrix is: 3.9598226605128524
极客教程