Rotating a matrix program in python

In this tutorial, we will see how to rotate a matrix in Python. We will learn how to transpose a matrix and reverse its rows to achieve the desired rotation. We will also create a function that can rotate any matrix of any size. 

Rotating a matrix is a common operation in many computer science applications. It involves reorganizing the elements of a matrix such that the rows become columns and vice versa. In this tutorial, we will be discussing how to implement matrix rotation in Python.

Rotating a matrix

Let’s learn this with some easy examples,

  1. First, declare the two variables to get input for rows and columns.
a = int(input("Enter the number of rows: "))
b = int(input("Enter the number of columns: "))

2. Input for rotating the matrix.

m = []
for i in range(a):
    n = []
    for j in range(b):
        j = int(input("Enter the value in the place of matrix ["+str(i)+"] ["+str(j)+"] : "))
        n.append(j)
    m.append(n)

3.  It is an optional step that prints the entered matrix in the output.

print("The entered matrix is: ")
for i in range(a):
    for j in range(b):
        print(m[i][j], end = " ")
    print()

4. We need to create a function that rotates the given matrix.

def rotate(m):
    n = []
    for i in  range(len(m)):
        c = []
        for j in range(len(m[0])):
            c.append(m[j][i])
        n.append(c)
    for i in range(len(n)):
        for  j in range(len(n[0])-1, -1, -1):
            print(n[i][j], end = " ")
        print()

print("The Rotated Matrix is: ")
rotate(m)

Output:

The entered matrix is:
1 2 3
4 5 6
7 8 9
The Rotated Matrix is:
7 4 1
8 5 2
9 6 3

Leave a Comment

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

Scroll to Top