0
0
NumpyHow-ToBeginner ยท 3 min read

How to Multiply Arrays in NumPy: Syntax and Examples

To multiply arrays in NumPy element-wise, use the * operator or numpy.multiply(). For matrix multiplication, use the @ operator or numpy.dot().
๐Ÿ“

Syntax

NumPy provides two main ways to multiply arrays:

  • Element-wise multiplication: multiplies each element of one array by the corresponding element of another array of the same shape.
  • Matrix multiplication: performs the dot product of two arrays following linear algebra rules.

Here is the syntax for both:

python
import numpy as np

# Element-wise multiplication
result_elementwise = array1 * array2
# or
result_elementwise_func = np.multiply(array1, array2)

# Matrix multiplication
result_matrix = array1 @ array2
# or
result_matrix_func = np.dot(array1, array2)
๐Ÿ’ป

Example

This example shows element-wise multiplication and matrix multiplication of two arrays.

python
import numpy as np

# Define two 2x2 arrays
array1 = np.array([[1, 2], [3, 4]])
array2 = np.array([[5, 6], [7, 8]])

# Element-wise multiplication
elementwise = array1 * array2

# Matrix multiplication
matrix_mult = array1 @ array2

print("Element-wise multiplication:\n", elementwise)
print("Matrix multiplication:\n", matrix_mult)
Output
Element-wise multiplication: [[ 5 12] [21 32]] Matrix multiplication: [[19 22] [43 50]]
โš ๏ธ

Common Pitfalls

Common mistakes when multiplying arrays in NumPy include:

  • Using * when you want matrix multiplication (it does element-wise instead).
  • Trying to multiply arrays with incompatible shapes without broadcasting.
  • Confusing np.dot() and np.multiply().

Here is an example showing the wrong and right way:

python
import numpy as np

# Define arrays
array1 = np.array([[1, 2], [3, 4]])
array2 = np.array([[5, 6], [7, 8]])

# Wrong: using * for matrix multiplication
wrong = array1 * array2  # This is element-wise, not matrix

# Right: use @ or np.dot for matrix multiplication
right = array1 @ array2

print("Wrong (element-wise):\n", wrong)
print("Right (matrix multiplication):\n", right)
Output
Wrong (element-wise): [[ 5 12] [21 32]] Right (matrix multiplication): [[19 22] [43 50]]
๐Ÿ“Š

Quick Reference

Summary of NumPy array multiplication methods:

OperationOperator / FunctionDescription
Element-wise multiplication* or np.multiply()Multiply arrays element by element
Matrix multiplication@ or np.dot()Perform linear algebra matrix multiplication
BroadcastingSupported with *Automatically expands smaller arrays to match shapes
โœ…

Key Takeaways

Use * or np.multiply() for element-wise multiplication of arrays.
Use @ or np.dot() for matrix multiplication following linear algebra rules.
Ensure arrays have compatible shapes for the chosen multiplication method to avoid errors.
Do not confuse element-wise multiplication with matrix multiplication; they produce different results.
Broadcasting allows element-wise multiplication of arrays with different but compatible shapes.