Piklu Dey
Piklu Dey

Reputation: 190

Broadcasting in numpy

I have just started to learn numpy an going through the scipy tutorials for numpy. My question is related to when broadcasting happens.

As suggested in the tutorial, two arrays are compatible if they follow certain conditions such as :

  1. They are equal
  2. One of them is 1

My question is, suppose I have the below two arrays:

import numpy as np

c1 = np.arange(10).reshape(2,5)
c2 = np.arange(8).reshape(2,4,1)
c3 = c1-c2

But the above operation gives me compatible/broadcast error as below:

ValueError: operands could not be broadcast together with shapes (2,5) (2,4,1)

When I diagrammatically represent these two arrays with pen and paper I get the operation cannot be performed, but I am not able to follow from the tutorial mentioned above, how the operation is not being successfully performed on the arrays. Please help me understand.

I know it is basic stuff, but this will be helpful for my understanding.

Regards

Upvotes: 2

Views: 710

Answers (1)

unutbu
unutbu

Reputation: 880797

This is the procedure for determining if two arrays can be broadcasted: Align the shapes with right-justification:

  2 5
2 4 1

Add 1's on the left, so that both shapes have the same number of axes (depicted below as columns):

1 2 5
2 4 1

Now compare down the columns. For broadcasting to work, the values in each column must either be the same or else one of the values has to equal 1.

In the second column, 2 does not equal 4, so broadcasting is not possible. (In the first and third columns the 1's make those axes compatible with broadcasting, but the entire arrays are not broadcastable because of the second column.)

Upvotes: 8

Related Questions