How to mirror a matrix across the main diagonal in Python

2 Answers

0 votes
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]

'''


 



answered Aug 28 by avibootz
0 votes
import numpy as np

matrix = np.array([
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
])

mirrored_matrix = matrix.T

print("Original Matrix:")
print(matrix)

print("\nMirrored Matrix:")
print(mirrored_matrix)




'''
run:

Original Matrix:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Mirrored Matrix:
[[1 4 7]
 [2 5 8]
 [3 6 9]]

'''

 



answered Aug 28 by avibootz
...