如何使用Numpy求解給定矩陣中所有元素的和?
在本程式中,我們將使用numpy庫中的sum()函式來求和numpy矩陣中的全部項。我們首先建立一個隨機的numpy矩陣,然後求出所有元素的和。
演算法
Step 1: Import numpy. Step 2: Create a random m×n matrix using the random() function. Step 3: Obtain the sum of all the elements in the matrix using the sum() function.
示例程式碼
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP