Python Program to Interchange the Diagonals of a matrix using predefined methods

The diagonals are nothing but crosswise elements of a matrix.

A square matrix has two diagonals. One is the Primary diagonal - located from the top left corner to the bottom right corner of a square matrix. And the second one is the Secondary diagonal - located from the top right to the bottom left corner.

Interchange the diagonals is nothing but changing the primary and secondary diagonal elements of a matrix.

See the below scenarios to understand it briefly

Input Output Scenarios

Assume we have a square matrix. And output matrix will be the resultant matrix whose diagonals are interchanged.

Input matrix:
[1, 3, 4]
[4, 5, 6]
[7, 8, 3]
Output matrix:
[4, 3, 1]
[4, 5, 6]
[3, 8, 7]


Let’s consider a 4X4 matrix.

Input matrix:
['o', 't', 'l', 'K']
['v', 'P', 's', 'm']
['E', 's', 'X', 'c']
['e', 'p', 'O', 'j']

Output matrix:
['K', 't', 'l', 'o']
['v', 's', 'P', 'm']
['E', 's', 'X', 'c']
['j', 'p', 'O', 'e']


Using Python List Methods

In python index(), pop(), insert(), and append() methods are list methods. And here the matrix is created by using the list of lists so that we can use these list methods to interchange diagonals.

• index() − The index() method returns the position where the given value is present at the first occurrence.

• pop() − The pop method removes the element at the specified position. By default, it removes the last element.

• insert() − This method can be used to insert an element at any desired position. This method takes two arguments, one is the element and the index at which the element has to be inserted.

• append()  method is used to add an element at the end of the list.

Example

In this example, the display() function will print the given matrix. And the interchangeDiagonals() function will interchange the elements.

#function for displaying matrix
def display(matrix):
for row in matrix:
print(row)
print()

# interchanging the diagonals elements
def interchangeDiagonals(matrix):
for row in matrix:
if matrix.index(row) != len(matrix) // 2:
temp1 = row[-1]
temp2 = row[0]
row.pop()
row.pop(0)
row.insert(0, temp1)
row.append(temp2)
return matrix

# input matrix
matrix = [[1, 3, 4], [4, 5, 6], [7, 8, 3]]

# displaying original matrix
print("Original matrix: ")
display(matrix)

# displaying changed matrix
print("Changed matrix: ")
display(interchangeDiagonals(matrix))


Output

Original matrix:
[1, 3, 4]
[4, 5, 6]
[7, 8, 3]

Changed matrix:
[4, 3, 1]
[4, 5, 6]
[3, 8, 7]


By using python list methods we have successfully interchanged the diagonal elements of the given matrix.

Note − The above method is applicable only for 3X3 matrices.

Updated on: 15-May-2023

86 Views