The dot product of two matrices is a scalar quantity calculated by multiplying the corresponding elements of the matrices and then summing them up. One common task when working with matrices is to extract the diagonal elements of the dot product. The diagonal of a dot product is a one-dimensional array that contains the products of the corresponding elements of the matrices that lie on the diagonal. To extract the diagonal of a dot product using NumPy, you can use the following techniques:
1. Using "indexing":
- You can use indexing to extract the diagonal elements of a matrix. This code performs matrix multiplication between two matrices
A
andB
using thenp.dot()
function. - Then, it extracts the diagonal elements of the resulting matrix
C
using indexing. The diagonal elements are the elements of the matrix where the row and column indices are the same, and they are returned as a 1D array. - Finally, the diagonal elements are printed as output.
2. Using "@" operator and "np.diag()":
- In NumPy, the
@
operator is used to perform matrix multiplication. This is equivalent to using thenp.dot()
function to perform matrix multiplication. - This code creates two matrices
A
andB
, takes their dot product using the@
operator, and then extracts the diagonal elements of the resulting matrix using thenp.diag()
function, storing them in the “diagonal” variable. - The diagonal elements of a matrix are those that lie on the main diagonal from the top left corner to the bottom right corner of the matrix. This code prints the diagonal elements of the dot product of
A
andB
.
3. Using "np.matmul()" and "np.diag()":
- In NumPy,
np.matmul()
performs the same functionality asnp.dot()
, used to perform matrix multiplication. - This code creates two matrices
A
andB
, computes their dot product using thenp.matmul()
function, and extracts the diagonal elements of the resulting matrix using thenp.diag()
function. - The resulting diagonal elements are then printed.