In this problem, we will find the sum of all the rows and all the columns separately. We will use the sum() function for obtaining the sum.
Step 1: Import numpy. Step 2: Create a numpy matrix of mxn dimension. Step 3: Obtain the sum of all the rows. Step 4: Obtain the sum of all the columns.
import numpy as np a = np.matrix('10 20; 30 40') print("Our matrix: \n", a) sum_of_rows = np.sum(a, axis = 0) print("\nSum of all the rows: ", sum_of_rows) sum_of_cols = np.sum(a, axis = 1) print("\nSum of all the columns: \n", sum_of_cols)
Our matrix: [[10 20] [30 40]] Sum of all the rows: [[40 60]] Sum of all the columns: [ ]
The np.sum() function takes an additional matrix called the 'axis'. Axis takes two values. Either 0 or 1. If axis=0, it tells the sum() function to consider only the rows. If axis = 1, it tells the sum() function to consider only the columns.