Clockwise and CounterClockwise Rotation of Matrix using NumPy in Python 3

In this tutorial, we will learn the clockwise and counterclockwise rotation of matrix using NumPy library in Python. We are providing an easy example of each one for a better understanding.

Let’s look at the points below to understand what we are exactly going to do:

  • rot90 will be used which is a built-in function.
  • Rotates the matrix by 90, 180 degrees as per requirement.
  • Rotates the matrix in Clockwise and Counterclockwise as per requirement.

The image given below is the clockwise rotation of a matrix by 90 degrees.

Clockwise & Counterclockwise Rotation of matrix using numpy python

Similarly, in the anti-clockwise rotation, the direction shown in the image will reverse.

Now, let’s take a look in the code snippet.

PROGRAM:

import numpy as np #clockwise,anticlockwise rotation of matrix
n=int(input("Number of Rows of the Square Matrix:"))
arr=[]
print("Enter elements of Matrix:")
for i in range(n):
    l=list(map(int,input().split(",")))
    arr.append(l)
print("The given Matrix is:")
for i in range(n):
    for j in range(n):
        print(arr[i][j],end=" ")
    print()
m=np.array(arr,int)
s=input("Anticlockwise/Clockwise:")
d=input("Degrees:")
degrees={"90":1,"180":2,"270":3}
if(s=="Anticlockwise" or s=="ANTICLOCKWISE" or s=="aNTICLOCKWISE"):
    m=np.rot90(m,degrees[d])
else:
    m=np.rot90(m,4-degrees[d])
print("The Matrix after rotation by the given degree.")
for i in range(n):
    for j in range(n):
        print(m[i][j],end=' ')
    print()

OUTPUT 1:

Number of Rows of the Square Matrix:3
Enter elements of Matrix:
1,2,3
4,5,6
7,8,9
The given Matrix is:
1 2 3 
4 5 6 
7 8 9 
Anticlockwise/Clockwise:Clockwise
Degrees:90
The Matrix after rotation by the given degree.
7 4 1 
8 5 2 
9 6 3

OUTPUT 2:

Number of Rows of the Square Matrix:4
Enter elements of Matrix:
1,2,3,4
4,5,6,7
8,9,1,2
6,4,5,3
The given Matrix is:
1 2 3 4 
4 5 6 7 
8 9 1 2 
6 4 5 3 
Anticlockwise/Clockwise:Anticlockwise
Degrees:90
The Matrix after rotation by the given degree.
4 7 2 3 
3 6 1 5 
2 5 9 4 
1 4 8 6

That’s it… We have successfully been able to rotate our matrix clockwise and counterclockwise using the NumPy module in Python 3.

Previously there was a slight mistake in the code and now I have fixed it.

Leave a Reply

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