According to the documentation (https://docs.scipy.org/doc/numpy/reference/ufuncs.html), two arrays are broadcastable if one of the following conditions are true:
- The arrays all have exactly the same shape.
- The arrays all have the same number of dimensions and the length of each dimensions is either a common length or 1.
- Arrays that have too few dimensions can have their shapes prepended with a dimension of length 1 to satisfy property 2.
I tried to implement this in python, but having a trouble in understanding the 2nd and 3rd rule. Not getting the answer that I am expecting, but I want to know what error that I am making in my code and a possible solution to this error.
# Broadcastable if:
# The arrays all have exactly the same shape.
if a.shape == b.shape:
result = True
# The arrays all have the same number of dimensions
elif len(a.shape) == len(b.shape):
# and the length of each dimensions is either a common length or 1.
for i in len(a.shape):
if len(a.shape[i] != 1):
result = False
else:
result = True
# Arrays that have too few dimensions can have their shapes prepended with a dimension of length 1 to satisfy property 2
elif a.shape == () or b.shape == ():
result = True
else:
result = False
return result