Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
In linear algebra, statistics, and machine learning, square matrices with ones along the main diagonal—known as Identity Matrices—act as the multiplicative identity element (analogous to the number 1 in scalar arithmetic). NumPy provides dedicated functions to construct identity matrices and manipulate matrix diagonals.
Both functions generate matrices with ones along the diagonal and zeros elsewhere, but np.eye() is significantly more flexible:
In np.eye(), the k parameter shifts the diagonal of ones:
k = 0 (Default): Main diagonal.k > 0 (Positive): Shifts the diagonal above the main diagonal (super-diagonal).k < 0 (Negative): Shifts the diagonal below the main diagonal (sub-diagonal).The np.diag() function performs two completely different operations depending on what you pass into it:
When passed a 2D matrix, it extracts the diagonal elements into a 1D vector:
When passed a 1D vector, it constructs a 2D square matrix with those values along the diagonal and zeros everywhere else:
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Inspecting Array Attributes (shape, ndim, size, itemsize) | 1D Array Indexing, Slicing & Step Strides |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.