What is the best way to test whether an array can be broadcast to a given shape?
The \"pythonic\" approach of try
ing doesn\'t work for my case, because the
If you just want to avoid materializing an array with a given shape, you can use as_strided:
import numpy as np
from numpy.lib.stride_tricks import as_strided
def is_broadcastable(shp1, shp2):
x = np.array([1])
a = as_strided(x, shape=shp1, strides=[0] * len(shp1))
b = as_strided(x, shape=shp2, strides=[0] * len(shp2))
try:
c = np.broadcast_arrays(a, b)
return True
except ValueError:
return False
is_broadcastable((1000, 1000, 1000), (1000, 1, 1000)) # True
is_broadcastable((1000, 1000, 1000), (3,)) # False
This is memory efficient, since a and b are both backed by a single record