Skip to content

Instantly share code, notes, and snippets.

@colematt
Created December 5, 2024 04:14
Show Gist options
  • Save colematt/8f6c198524f16901052173c069cd37b2 to your computer and use it in GitHub Desktop.
Save colematt/8f6c198524f16901052173c069cd37b2 to your computer and use it in GitHub Desktop.
[Matrix Transformations Without Numpy] #python
#!/usr/bin/env python3
def transpose(matrix):
"Swap the rows and columns of a 2-D matrix."
return [list(row) for row in zip(*matrix, strict=True)]
def rotate(matrix):
"""
Rotate a matrix 90 degrees clockwise
"""
return list(list(row) for row in zip(*matrix[::-1]))
def reflect(matrix, axis):
"""
Reflect a matrix across an axis
If axis=0, reflect vertically (up-down)
If axis=1, reflect horizontally (left-right)
"""
if axis == 0:
return list(reversed(matrix))
elif axis == 1:
return [list(reversed(row)) for row in matrix]
else:
raise ValueError("Unknown axis: %i" % axis)
def invert(matrix):
"""
Reflect a matrix both horizontally and vertically
"""
return reflect(reflect(matrix,0),1)
def translate(matrix, rows, cols):
"""
Translate a matrix by a number of rows and columns.
Positive values cause rightward or downward translation.
"""
return [[matrix[(r+rows) % len(matrix)][(c+cols) % len(matrix[r])]
for c in range(len(matrix[r]))] for r in range(len(matrix))]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment