Home »
Python »
Python Programs
Reverse Diagonal Elements of Matrix in Python
In this tutorial, we will learn how to get the reverse diagonal elements of matrix from right to left in Python?
By Pranit Sharma Last updated : May 14, 2023
Diagonals of a matrix are defined as a set of those points where the row and the column coordinates are the same. Usually, when we read an array, the diagonal is always considered from left to right. Here, we need to get the diagonal elements from right to left.
Problem statement
Suppose that we are given a 2D NumPy array i.e., matrix and we need to get the reverse diagonal elements from right to left.
Example
Consider the below example with sample input and output:
Input:
[[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]]
Output:
[[ 4 3 2 1]
[ 8 7 6 5]
[12 11 10 9]
[16 15 14 13]]
How to get reverse diagonal elements of matrix?
To get reverse diagonal elements of the matrix, you can use numpy.fliplr() method, it accepts an array_like parameter (which is the matrix) and reverses the order of elements along axis 1 (left/right). For a 2D array (matrix), it flips the entries in each row in the left/right direction.
Let us understand with the help of examples.
Python examples to get reverse diagonal elements of matrix
Consider the following examples to understand the concept of getting reverse diagonal elements of a matrix from right to left in Python.
Example 1
# Import numpy
import numpy as np
# Creating a numpy array
arr = np.diag([1.0, 2.0, 3.0])
# Display Original array
print("Original array 1:\n", arr, "\n")
# Reversing the diagonal
res = np.fliplr(arr)
# Display result
print("Result:\n", res, "\n")
Output
Original array 1:
[[1. 0. 0.]
[0. 2. 0.]
[0. 0. 3.]]
Result:
[[0. 0. 1.]
[0. 2. 0.]
[3. 0. 0.]]
Example 2
# Import numpy
import numpy as np
# matrix
matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
# Display the matrix
print("Original Matrix:\n", matrix, "\n")
# Reversing the diagonal
res = np.fliplr(matrix)
# Display result
print("Result:\n", res, "\n")
Output
Original Matrix:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
Result:
[[ 4 3 2 1]
[ 8 7 6 5]
[12 11 10 9]
[16 15 14 13]]
Python NumPy Programs »