- Program to rotate square matrix by 90 degrees counterclockwise in Python
- Program to rotate square matrix by 90 degrees counterclockwise in Python
- Example
- Input
- Output
- How to rotate a matrix (nested list) counter clockwise by 90 degrees
- A function that rotates a matrix X degrees clockwise or counter clockwise
- Python3 Program to Inplace rotate square matrix by 90 degrees | Set 1
- Rotate a Matrix by 90 Degrees in python with User input
- Rotate a Matrix by 90 Degrees (Clockwise)
- Algorithm
- Source Code
- Output-1
- Output-2
- numpy.rot90#
Program to rotate square matrix by 90 degrees counterclockwise in Python
But that being said, numpy offers a function to rotate matrices: Solution 3: Other option is to use scipy.ndimage.rotate Question: I’m trying to write a function, , that accepts two parameters, a 4×4 matrix and a number that represents the degrees to rotate the matrix. So I rotate the matrix using those two functions, according to the input of degrees.
Program to rotate square matrix by 90 degrees counterclockwise in Python
Suppose we have a square matrix, we have to rotate it 90 degrees counter-clockwise.
To solve this, we will follow these steps −
- if matrix is empty, then
- return a blank list
- reverse the row
- for j in range 0 to i−1, do
- swap matrix[i, j] and matrix[j, i]
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, matrix): if not matrix or not matrix[0]: return [] n = len(matrix) for row in matrix: row.reverse() for i in range(n): for j in range(i): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] return matrix ob = Solution() matrix = [ [1, 4, 7], [2, 5, 8], [3, 6, 9] ] print(ob.solve(matrix))
Input
Output
In Python, how do I rotate a matrix 90 degrees, Sorted by: 12. Here is the counter clockwise matrix rotation as one line in pure python (i.e., without numpy): new_matrix = [ [m [j] [i] for j in range (len (m))] for i in range (len (m [0])-1,-1,-1)] If you want to do this in a function, then. def rotate_matrix ( m ): return [ [m [j] [i] for j in range (len (m))] for i in range (len (m … Code sampledef rotate_matrix( m ):return [[m[j][i] for j in range(len(m))] for i in range(len(m[0])-1,-1,-1)]Feedback
How to rotate a matrix (nested list) counter clockwise by 90 degrees
I’m trying to rotate a matrix counter clockwise by 90 degrees. For example, if:
then the result should be
rez = [[m[j][i] for j in range(len(m))] for i in range(len(m[0]))] for row in rez: print(row)
This is close, but the rows would need to be reverses. Does anyone know a simple way to rotate this matrix counter clockwise by 90 degrees?
You could do the following:
m = [[1, 2, 3], [2, 3, 3], [5, 4, 3]] result = list(map(list, zip(*m)))[::-1] print(result)
With map(list, zip(*m)) you create an iterable of the columns, and with the expression list(. )[::-1] you convert that iterable into a list and reverse it.
What you here basically do is map a matrix A to a matrix B such that:
In case you rotate elements, that means that if you rotate an n×m -matrix, then that means that:
So we can calculate this as:
rez = [[m[j][ni] for j in range(len(m))] for ni in range(len(m[0])-1, -1, -1)]
which is thus the transpose, but than «reversed». Using indices is however typically not how you do such processing in Python, since now it works only for items that are subscriptable, so I advice you to look for a more elegant solution.
But that being said, numpy offers a numpy.rot90 function to rotate matrices:
>>> np.rot90(m) array([[3, 3, 3], [2, 3, 4], [1, 2, 5]])
Other option is to use scipy.ndimage.rotate
Rotate an array.
The array is rotated in the plane defined by the two axes given by the axes parameter using spline interpolation of the requested order.
import numpy as np from scipy import ndimage m = np.matrix([[1,2,3], [2,3,3], [5,4,3]]) ndimage.rotate(m, 90.0) #angle as float.
Out: array([[3, 3, 3], [2, 3, 4], [1, 2, 5]])
Same result you can get by using the zip() function to transpose rows and columns of a 5.1.4. Nested List then reverse the nested list with [::-1] + put in a np.matrix :
matrix = [[1, 2, 3], [2, 3, 3], [5, 4, 3]] np.matrix(list(zip(*matrix)))[::-1]
Out: matrix([[3, 3, 3], [2, 3, 4], [1, 2, 5]])
Python3 Program to Inplace rotate square matrix by 90, Approach: To solve the question without any extra space, rotate the array in form of squares, dividing the matrix into squares or cycles. For example, A 4 X 4 matrix will have 2 cycles. The first cycle is formed by its 1st row, last column, last row and 1st column. The second cycle is formed by 2nd row, second-last …
A function that rotates a matrix X degrees clockwise or counter clockwise
I’m trying to write a function, rotateByX , that accepts two parameters, a 4×4 matrix and a number that represents the degrees to rotate the matrix. The degrees are 90, 180, 270,360.. and so on. If the entered degree is positive then the matrix rotates to the right clockwise. If it’s negative (e.g -90,-180..) then the matrix rotates to the left, counter clockwise. I was able to solve a similar problem, in which I needed only to rotate 90 degrees clockwise . I used this funnction in my code here, and also made another function that rotates 90 degrees counter clockwise . So I rotate the matrix using those two functions, according to the input of degrees.
My code:
def rotate90_Counter(m): return [[m[j][i] for j in range(len(m))] for i in range(len(m[0])-1,-1,-1)] def rotateByX(m,X): rotations = (X//90)%4 if X >= 0: for p in range(rotations): m= rotate90_clockwise(m) elif X < 0: for s in range(rotations): m= rotate_90_Counter(m) return m m = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] rotateByX(m, -90)
This is currently working only when the input of degrees, X, is positive. So 90, 180, 270.. it rotates beautifuly. But with negative X it rotates to the right (clockwise) rather than to the left.
rotateByX calculates a number rotations which is the number of times to rotate clockwise by 90 degrees in order to achieve a rotation by X degrees clockwise (which is equal to -X degrees counterclockwise).
So just always rotate clockwise rotations times. Don't rotate counterclockwise ever. Drop the if X >= 0 / elif X < 0 , all the relevant information about X is already contained in rotations .
def rotateByX(m, X): rotations = (X // 90) % 4 for p in range(rotations): m = rotate90_clockwise(m) return m
Python - How can I rotate a matplotlib plot through 90, I'd like to rotate the top left quadrant subplot through 90deg counterclockwise, so that the x-axis of that plot lies along the y-axis of the 2-d plot. For the subplot, I realize I could flip the x and y data, rotate the axis labels, create a plot title on the left hand side, etc.
Python3 Program to Inplace rotate square matrix by 90 degrees | Set 1
An approach that requires extra space is already discussed here.
Approach: To solve the question without any extra space, rotate the array in form of squares, dividing the matrix into squares or cycles. For example,
A 4 X 4 matrix will have 2 cycles. The first cycle is formed by its 1st row, last column, last row and 1st column. The second cycle is formed by 2nd row, second-last column, second-last row and 2nd column. The idea is for each square cycle, swap the elements involved with the corresponding cell in the matrix in anti-clockwise direction i.e. from top to left, left to bottom, bottom to right and from right to top one at a time using nothing but a temporary variable to achieve this.
Demonstration:First Cycle (Involves Red Elements) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Moving first group of four elements (First elements of 1st row, last row, 1st column and last column) of first cycle in counter clockwise. 4 2 3 16 5 6 7 8 9 10 11 12 1 14 15 13 Moving next group of four elements of first cycle in counter clockwise 4 8 3 16 5 6 7 15 2 10 11 12 1 14 9 13 Moving final group of four elements of first cycle in counter clockwise 4 8 12 16 3 6 7 15 2 10 11 14 1 5 9 13 Second Cycle (Involves Blue Elements) 4 8 12 16 3 6 7 15 2 10 11 14 1 5 9 13 Fixing second cycle 4 8 12 16 3 7 11 15 2 6 10 14 1 5 9 13
- There is N/2 squares or cycles in a matrix of side N. Process a square one at a time. Run a loop to traverse the matrix a cycle at a time, i.e loop from 0 to N/2 – 1, loop counter is i
- Consider elements in group of 4 in current square, rotate the 4 elements at a time. So the number of such groups in a cycle is N – 2*i.
- So run a loop in each cycle from x to N – x – 1, loop counter is y
- The elements in the current group is (x, y), (y, N-1-x), (N-1-x, N-1-y), (N-1-y, x), now rotate the these 4 elements, i.e (x, y)
- Print the matrix.
Rotate a Matrix by 90 Degrees in python with User input
In this post, you will learn a python program to rotate a matrix by 90 degrees in clockwise directions with a very simple explanation and algorithm.
Rotate a Matrix by 90 Degrees (Clockwise)
Rotating a matrix by 90 degrees in the clockwise direction using python is a very simple task. You just have to do two simple steps, the first step is to transpose the given matrix and the second step is to reverse the rows of the transpose matrix.
Now let’s see the algorithm for the above steps
Algorithm
1. Define a function rotate_matrix(matrix) that takes a matrix as an input. 2. Transpose the matrix using the zip function:
-> Create an empty list called transposed .
-> Iterate over the rows of the matrix (using zip(*matrix) ).
-> For each row, append a list version of the row to transposed .3. Reverse the rows of the transposed matrix:
-> Create an empty list called rotated .
-> Iterate over the rows of the transposed matrix.
-> For each row, append the reversed row to rotated .4. Return the rotated matrix. From the above algorithm, we understood how to implement the python program to rotate a matrix by 90 degrees in a clockwise direction.
But before writing a program few programming concepts you have to know:
Source Code
def rotate_matrix(matrix): transposed = [] for row in zip(*matrix): transposed.append(list(row)) rotated = [] for row in transposed: rotated.append(row[::-1]) return rotated # User input rows = int(input('Enter number of rows: ')) cols = int(input('Enter number of column: ')) matrix = [[int(input(f"column -> ENter element:")) for j in range(cols)] for i in range(rows) ] print() # for new line print('Given matrix :') # print matrix for row in matrix: print(row) # calling a function rotate_90 = rotate_matrix(matrix) print() # for new line print('Matrix after rotated by 90 degree') # print rotated matrix for row in rotate_90: print(row)
Output-1
Enter number of rows: 3
Enter number of column: 3
column 1 -> ENter 1 element:1
column 2 -> ENter 1 element:2
column 3 -> ENter 1 element:3
column 1 -> ENter 2 element:4
column 2 -> ENter 2 element:5
column 3 -> ENter 2 element:6
column 1 -> ENter 3 element:7
column 2 -> ENter 3 element:8
column 3 -> ENter 3 element:9
Given matrix :
[1, 2, 3][4, 5, 6][7, 8, 9]Matrix after rotated by 90 degree
[7, 4, 1][8, 5, 2][9, 6, 3]Output-2
Enter number of rows: 2
Enter number of column: 2
column 1 -> ENter 1 element:1
column 2 -> ENter 1 element:2
column 1 -> ENter 2 element:3
column 2 -> ENter 2 element:4
Given matrix :
[1, 2][3, 4]Matrix after rotated by 90 degree
[3, 1][4, 2]numpy.rot90#
Rotate an array by 90 degrees in the plane specified by axes.
Rotation direction is from the first towards the second axis. This means for a 2D array with the default k and axes, the rotation will be counterclockwise.
Parameters : m array_like
Array of two or more dimensions.
Number of times the array is rotated by 90 degrees.
axes (2,) array_like
The array is rotated in the plane defined by the axes. Axes must be different.
Reverse the order of elements in an array along the given axis.
Flip an array horizontally.
rot90(m, k=1, axes=(1,0)) is the reverse of rot90(m, k=1, axes=(0,1))
rot90(m, k=1, axes=(1,0)) is equivalent to rot90(m, k=-1, axes=(0,1))
>>> m = np.array([[1,2],[3,4]], int) >>> m array([[1, 2], [3, 4]]) >>> np.rot90(m) array([[2, 4], [1, 3]]) >>> np.rot90(m, 2) array([[4, 3], [2, 1]]) >>> m = np.arange(8).reshape((2,2,2)) >>> np.rot90(m, 1, (1,2)) array([[[1, 3], [0, 2]], [[5, 7], [4, 6]]])