Matrix manipulation in Python


We can easily perform matrix manipulation in Python using the Numpy library. NumPy is a Python package. It stands for 'Numerical Python'. It is a library consisting of multidimensional array objects and a collection of routines for processing of array. Using NumPy, mathematical and logical operations on arrays can be performed.

Install and Import Numpy

To install Numpy, use pip −

pip install numpy

Import Numpy −

import numpy

Add, Subtract, Divide and Multiply matrices

We will use the following Numpy methods for matrix manipulations −

  • numpy.add() − Add two matrices

  • numpy.subtract() − Subtract two matrices

  • numpy.divide() − Divide two matrices

  • numpy.multiply() − Multiply two matrices

Let us now see the code −

Example

import numpy as np # Two matrices mx1 = np.array([[5, 10], [15, 20]]) mx2 = np.array([[25, 30], [35, 40]]) print("Matrix1 =\n",mx1) print("\nMatrix2 =\n",mx2) # The addition() is used to add matrices print ("\nAddition of two matrices: ") print (np.add(mx1,mx2)) # The subtract() is used to subtract matrices print ("\nSubtraction of two matrices: ") print (np.subtract(mx1,mx2)) # The divide() is used to divide matrices print ("\nMatrix Division: ") print (np.divide(mx1,mx2)) # The multiply()is used to multiply matrices print ("\nMultiplication of two matrices: ") print (np.multiply(mx1,mx2))

Output

Matrix1 =
 [[ 5 10]
 [15 20]]

Matrix2 =
[[25 30]
 [35 40]]

Addition of two matrices:
[[30 40]
 [50 60]]

Subtraction of two matrices:
[[-20 -20]
 [-20 -20]]

Matrix Division:
[[0.2 0.33333333]
 [0.42857143 0.5 ]]

Multiplication of two matrices:
[[125 300]
 [525 800]]

Summation of matrix elements

The sum() method is used to find the summation −

Example

import numpy as np # A matrix mx = np.array([[5, 10], [15, 20]]) print("Matrix =\n",mx) print ("\nThe summation of elements=") print (np.sum(mx)) print ("\nThe column wise summation=") print (np.sum(mx,axis=0)) print ("\nThe row wise summation=") print (np.sum(mx,axis=1))

Output

Matrix =
 [[ 5 10]
 [15 20]]

The summation of elements=
50

The column wise summation=
[20 30]

The row wise summation=
[15 35]

Transpose a Matrix

The .T property is used to find the Transpose of a Matrix −

Example

import numpy as np # A matrix mx = np.array([[5, 10], [15, 20]]) print("Matrix =\n",mx) print ("\nThe Transpose =") print (mx.T)

Output

Matrix =
 [[ 5 10]
 [15 20]]

The Transpose =
[[ 5 15]
 [10 20]]

Updated on: 11-Aug-2022

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements