DEV Community

Cover image for Numpy Dot Function
Labby for LabEx

Posted on • Originally published at labex.io

Numpy Dot Function

β‘  Understand the Syntax of numpy.dot()

The syntax required for using the dot() function is as follows:

numpy.dot(a, b, out=None)
Enter fullscreen mode Exit fullscreen mode

Where:

  • a is the first parameter. If "a" is complex, then its complex conjugate is used for the calculation of the dot product.
  • b is the second parameter. If "b" is complex, then its complex conjugate is used for the calculation of the dot product.
  • out is the output argument. If it is not used, then it must have the exact kind that would be returned. Otherwise, it must be C-contiguous and its dtype must be the dtype that would be returned for dot(a, b).

β‘‘ Calculate the Dot Product of Scalars and 1D Arrays

In this step, we will use the dot() function to calculate the dot product of scalars and 1D arrays.

import numpy as np

# Calculate the dot product of scalar values
a = np.dot(8, 4)
print("The dot product of the above given scalar values is: ")
print(a)

# Calculate the dot product of two 1D arrays
vect_a = 4 + 3j
vect_b = 8 + 5j

dot_product = np.dot(vect_a, vect_b)
print("The dot product of two 1D arrays is: ")
print(dot_product)
Enter fullscreen mode Exit fullscreen mode

β‘’ Perform Matrix Multiplication with 2D Arrays

In this step, we will use the dot() function to perform matrix multiplication with 2D arrays.

import numpy as np

a = np.array([[50,100],[12,13]])
print("Matrix a is:")
print(a)

b = np.array([[10,20],[12,21]])
print("Matrix b is:")
print(b)

dot = np.dot(a, b)
print("The dot product of matrices a and b is:")
print(dot)
Enter fullscreen mode Exit fullscreen mode

β‘£ Error Handling

In this step, we will explore the ValueError that is raised when the last dimension of a is not the same size as the second-to-last dimension of b.

import numpy as np

a = np.array([[1, 2, 3], [4, 5, 6]])
b = np.array([[7, 8], [9, 10], [11, 12], [13, 14]])

# Error handling
error = np.dot(a, b)
print(error)
Enter fullscreen mode Exit fullscreen mode

β‘€ Summary

In this lab, we covered the dot() function of the Numpy library. We learned how to use this function with its syntax, and the values returned by the function were explained with the help of code examples. We also explored the error handling of the function.


Want to learn more?

Join our Discord or tweet us @WeAreLabEx ! πŸ˜„

Top comments (0)