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 intent is to have lazy evaluation of the operation.
I’m asking how to implement is_broadcastable
below:
JavaScript
x
8
1
>>> x = np.ones([2,2,2])
2
>>> y = np.ones([2,2])
3
>>> is_broadcastable(x,y)
4
True
5
>>> y = np.ones([2,3])
6
>>> is_broadcastable(x,y)
7
False
8
or better yet:
JavaScript
1
2
1
>>> is_broadcastable(x.shape, y.shape)
2
Advertisement
Answer
I really think you guys are over thinking this, why not just keep it simple?
JavaScript
1
8
1
def is_broadcastable(shp1, shp2):
2
for a, b in zip(shp1[::-1], shp2[::-1]):
3
if a == 1 or b == 1 or a == b:
4
pass
5
else:
6
return False
7
return True
8