def mirror_matrix_across_diagonal(matrix):
"""
Mirrors a square matrix across its main diagonal.
Args:
matrix (list of list of int/float): A 2D square matrix.
Returns:
The mirrored (transposed) matrix.
"""
# Ensure the matrix is square
n = len(matrix)
for row in matrix:
if len(row) != n:
raise ValueError("The input matrix must be square (NxN).")
# Swap elements across the diagonal
for i in range(n):
for j in range(i + 1, n): # Only iterate over the upper triangle
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
return matrix
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print("Original Matrix:")
for row in matrix:
print(row)
# Mirror the matrix
mirrored_matrix = mirror_matrix_across_diagonal(matrix)
print("\nMirrored Matrix:")
for row in mirrored_matrix:
print(row)
'''
run:
Original Matrix:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Mirrored Matrix:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
'''