Explanation:
๐น Import NumPy Library
import numpy as np
This line imports the NumPy library and assigns it the alias np for easy use.
๐น Create Matrix
mat = np.array([[1, 2], [3, 4]])
This line creates a 2×2 NumPy matrix with the given elements.
๐น Initialize Sum Variable
s = 0
This line initializes the variable s to store the sum of diagonal elements.
๐น Loop Through Diagonal Elements
for i in range(len(mat)):
This loop runs through the indices of the matrix rows.
๐น Add Diagonal Elements
s += mat[i][i]
This line accesses and adds each diagonal element of the matrix to s.
๐น Display Result
print(s)
This line prints the final sum of the diagonal elements.
✅ Output
5

0 Comments:
Post a Comment