What are the methods for extracting the diagonal of a dot product?

I had a query regarding this topic. I came across this piece of code:

Although this code is itself an efficient and fast way to yield my result, I still wanted other alternatives. Can anyone provide me with the relevant solutions?

1 Like

Hello @safiaa.02, I know another efficient method to accomplish this task, which involves using the np.matmul() function of NumPy to perform matrix multiplication, and then using the np.diag() function to extract the diagonal elements of the resulting matrix. Here is an example code that demonstrates this technique:

This method is particularly useful when you need to multiply large matrices, as it avoids the overhead of looping over each element of the matrix. Instead, it performs the multiplication in a more efficient way, resulting in faster computation times.