Let’s explore how to efficiently rotate a matrix in Numpy, where we’ll uncover some clever tricks along the way.
Rotating by 90 Degrees
Rotating a matrix by 90 degrees using Numpy is straightforward with the dedicated rot90 method:
import numpy as np my_array = np.array([[11, 12, 13], [21, 22, 23], [31, 32, 33]]) print(f"This is my array: \n{my_array}") rotate_array = np.rot90(my_array) print(f"Array rotated: \n{rotate_array}")
Rotating by 270 Degrees
To perform a 270-degree rotation (equivalent to three rounds of 90-degree rotation counterclockwise), simply pass 3 as a parameter to the rot90 function:
import numpy as np my_array = np.array([[11, 12, 13], [21, 22, 23], [31, 32, 33]]) print(f"This is my array: \n{my_array}") rotate_array = np.rot90(my_array, 3) print(f"Array rotated 270 degrees: \n{rotate_array}")
This is 270 degrees rotation but we can also say that this is left rotation because this is how to rotate an matrix left direction.
Rotating by 180 Degrees
For a 180-degree rotation, use np.rot90(my_array, 2). Note that applying np.rot90(my_array, 4) will not alter the array.
You can also rotate the array over specific axes:
import numpy as np my_array = np.array([[11, 12, 13], [21, 22, 23], [31, 32, 33]]) print(f"This is my array: \n{my_array}") rotate_array = np.rot90(my_array, axes=(1, 0)) print(f"Array rotated over axes=(1, 0): \n{rotate_array}")
I used np.rot90(my_array, axes=(1, 0)) and this is how it got rotated.
In addition to rotating matrices, you can also flip them horizontally and vertically with Numpy. Here’s how:
Horizontal Flip
To flip a matrix horizontally, use np.fliplr():
import numpy as np my_array = np.array([[11, 12, 13], [21, 22, 23], [31, 32, 33]]) print(f"This is my array: \n{my_array}") horizontal_flip = np.fliplr(my_array) print(f"Array after horizontal flip: \n{horizontal_flip}")
Vertical Flip
For a vertical flip, employ np.flipud():
import numpy as np my_array = np.array([[11, 12, 13], [21, 22, 23], [31, 32, 33]]) print(f"This is my array: \n{my_array}") vertical_flip = np.flipud(my_array) print(f"Array after vertical flip: \n{vertical_flip}")
These simple Numpy functions allow you to achieve horizontal and vertical flips effortlessly, offering versatile options for manipulating matrices.