# Clockwise & CounterClockwise Rotation of Matrix using Numpy in Python3

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

## Clockwise & Counterclockwise Rotation of matrix using Numpy Library

Clockwise & Counterclockwise Rotation of a matrix using Numpy Library.

- 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.

Read more about Numpy Library here: http://www.numpy.org/

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

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

Also Read:

## Leave a Reply