numpy.matrix() in Python with example

Hello People! In this tutorial we are going to learn about numpy.matrix() in Python with example. In Python, a matrix object is similar to nested lists as they are multi dimensional. We will see how to create a matrix using numpy arrays. After this, we will see different matrix operations and examples for better understanding.

Introduction:

The numpy.matrix() in Python is used to return a matrix from a string of data. The matrix obtained is a 2D array. A matrix in Python is a rectangular Numpy array. It contains data stored in rows and columns. In matrix, the horizontal series of items are referred as “rows”, while the vertical series of items are called as “columns”.

In this tutorial, we will go through the following list of matrix operation methods.

  • Matrix addition
  • Matrix multiplication

NumPy Array In Python

import numpy as np
array = np.array([2,1,"sam"])
print(array)
print("Data type of array object:",type(array))

output:
['2' '1' 'sam']
Data type of array object: <class 'numpy.ndarray'>

Creating a Matrix Using NumPy Array: Example

Code:

import numpy as np
a = np.array([['A',12,24],['B',13,25],['C',14,26],['D',15,27],['E',16,28]])
matrix = np.reshape(a,(5,3))
print("The matrix is: \n",matrix)

Output:

The matrix is:
 [['A',12,24],['B',13,25],['C',14,26],['D',15,27],['E',16,28]]

Matrix Operations In Python

Python Matrix Addition:

We will add the two matrices and use the nested for loop through the given matrices.

code:

matrix1 = [[23,43,12],[43,13,55],[23,12,13]]
matrix2 = [[4,2,-1],[5,4,-34],[0,-4,3]]
matrix3 = [[0,1,0],[1,0,0],[0,0,1]]
matrix4 = [[0,0,0],[0,0,0],[0,0,0]]
matrices_length = len(matrix1)
for row in range(len(matrix1)):
    for column in range(len(matrix2[0])):
           matrix4[row][column] = matrix1[row][column] + matrix2[row][column] + matrix3[row][column]
print("The sum of the matrices is = ",matrix4)

Output:

The sum of the matrices is = [[27, 46, 11], [49, 17, 21], [23, 8, 17]]

Python Matrix Multiplication:

In Python @ is known as the multiplication operator. Let us see an example where we use this operator to multiply two matrices.

code:

import numpy as np
matrix1 = np.matrix('3,4;5,6')
matrix2 = np.matrix('4,6;8,2')
print(matrix1 @ matrix2)

Output:

[[44 26] [68 42]]

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top