Creation of 2D array and print the diagonal elements of the matrix in Python
2D array has rows and columns. The data is stored in row wise. Let us create a 2D array as follows.
Python code to create a 2D array of elements:
#import the built-in file numpy and develop an object np1
import numpy as np1
# Create a 2D array of elements with 2 rows and 2 columns
arr_2d = np1.arange(1, 5).reshape(2, 2)
#print the elements
print("2D Array elements are:\n", arr_2d)
here, is the output.
2D Array elements are:
[[1 2]
[3 4]]
If you want to change the rows and columns to 3. Use the
below code…
arr_2d = np1.arange(1, 10).reshape(3, 3)
It gives you the output as follows.
2D Array elements are:
[[1 2 3]
[4 5 6]
[7 8 9]]
If you want to print 4 rows and columns. Let this code helps…
arr_2d = np1.arange(1, 17).reshape(4, 4)
The output is
2D Array elements are:
[[ 1 2
3 4]
[ 5 6
7 8]
[ 9 10 11 12]
[13 14 15 16]]
Next program is to print the diagonal elements of a matrix.
Python program to print the diagonal elements of a matrix:
This program starts from creating a
3X3 matrix with elements. Next, print the diagonal elements by using len()
function. If you want to print the secondary diagonal number, use the same
function subtracted by 1.
Matrix1 = [
[11, 22, 33],
[44, 55, 66],
[76, 87, 69]
]
# Print main diagonal elements
print("Main diagonal elements:")
for i in range(len(matrix)):
print(matrix[i][i])
print("Secondary diagonal elements:")
for i in range(len(matrix)):
print(matrix[i][len(matrix)
- 1 - i])
Output:
Main diagonal elements:
11
55
69
Secondary diagonal elements:
33
55
76
That’s all. Thus the python program to create 2D array and print the diagonal elements of the matrix was done successfully. Keep Coding!!!!
Comments
Post a Comment