MasayoMusic
MasayoMusic

Reputation: 614

Subtracting one dimensional array (list of scalars) from 3 dimensional arrays using broadcasting

I have a one dimesional array of scalar values

Y = np.array([1, 2])

I also have a 3-dimensional array:

X = np.random.randint(0, 255, size=(2, 2, 3))

I am attempting to subtract each value of Y from X, so I should get back Z which should be of shape (2, 2, 2, 3) or maybe (2, 2, 2, 3).

I can"t seem to figure out how to do this via broadcasting.

I tried changing the change of Y:

Y = np.array([[[1, 2]]])

but not sure what the correct shape should be.

Upvotes: 0

Views: 385

Answers (2)

Mad Physicist
Mad Physicist

Reputation: 114320

Broadcasting lines up dimensions on the right. So you're looking to operate on a (2, 1, 1, 1) array and a (2, 2, 3) array.

The simplest way I can think of is using reshape:

Y = Y.reshape(-1, 1, 1, 1)

More generally:

Y = Y.reshape(-1, *([1] * X.ndim))

At most one of the arguments to reshape can be -1, indicating all the remaining size not accounted for by other dimensions.

To get Z of shape (2, 2, 2, 3):

Z = X - Y.reshape(-1, *([1] * X.ndim))

If you were OK with having Z of shape (2, 2, 3, 2), the operation would be much simpler:

Z = X[..., None] - Y

None or np.newaxis will insert a unit axis into the end of X's shape, making it broadcast properly with the 1D Y.

Upvotes: 2

Patol75
Patol75

Reputation: 4547

I am not entirely sure on which dimension you want your subtraction to take place, but X - Y will not return an error if you define Y such as Y = numpy.array([1,2]).reshape(2, 1, 1) or Y = numpy.array([1,2]).reshape(1, 2, 1).

Upvotes: 0

Related Questions