Broadcasting helps us multiply arrays of different shapes easily. It lets us find outer products without writing loops.
0
0
Broadcasting for outer products in NumPy
Introduction
When you want to multiply every element of one list by every element of another list.
When calculating combinations of values from two different sets.
When creating a grid of values from two arrays for plotting or analysis.
When you want to avoid slow loops and use fast array operations.
Syntax
NumPy
import numpy as np a = np.array([1, 2, 3]) b = np.array([4, 5]) # Reshape a to a column vector and b to a row vector outer_product = a[:, np.newaxis] * b # or use np.outer(a, b) for the same result
Adding np.newaxis changes the shape to allow broadcasting.
Broadcasting automatically expands arrays to compatible shapes.
Examples
Multiply each element of a by each element of b using broadcasting.
NumPy
import numpy as np a = np.array([1, 2, 3]) b = np.array([4, 5]) outer = a[:, np.newaxis] * b print(outer)
Use numpy's built-in outer function to get the same result.
NumPy
import numpy as np a = np.array([1, 2]) b = np.array([3, 4, 5]) outer = np.outer(a, b) print(outer)
Sample Program
This program shows two ways to compute the outer product of two arrays. First, it reshapes one array to a column and multiplies by the other array using broadcasting. Then, it uses numpy's built-in outer function. Both give the same result.
NumPy
import numpy as np # Define two arrays x = np.array([2, 4, 6]) y = np.array([1, 3]) # Compute outer product using broadcasting outer_product = x[:, np.newaxis] * y print('Outer product using broadcasting:') print(outer_product) # Compute outer product using numpy's outer function outer_function = np.outer(x, y) print('\nOuter product using np.outer:') print(outer_function)
OutputSuccess
Important Notes
Broadcasting works when one array can be 'stretched' to match the other's shape.
Using np.newaxis is a simple way to add a dimension for broadcasting.
np.outer is a convenient shortcut for outer products.
Summary
Broadcasting lets you multiply arrays of different shapes without loops.
Use np.newaxis to reshape arrays for broadcasting.
np.outer is a quick way to get outer products.