1

Suppose we create an numpy array like this:

x =  np.linspace(1,5,5).reshape(-1,1)

which results in this:

array([[ 1.],
   [ 2.],
   [ 3.],
   [ 4.],
   [ 5.]])

now we add the transpose of this array to it:

x + x.T

which results in this:

array([[  2.,   3.,   4.,   5.,   6.],
   [  3.,   4.,   5.,   6.,   7.],
   [  4.,   5.,   6.,   7.,   8.],
   [  5.,   6.,   7.,   8.,   9.],
   [  6.,   7.,   8.,   9.,  10.]])

I don't understand this because the two arrays have different dimensions (5x1 and 1x5) and I learned in linear algebra that we can only sum up matrices when they have the same dimension.

Edit: OK thanks, got it

4
  • 5
    Please read up on broadcasting - docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html. Commented Dec 2, 2017 at 19:43
  • Possible duplicate of Numpy array broadcasting rules Commented Dec 2, 2017 at 20:53
  • Instead of adding "Edit: OK thanks, got it" to your question, please mark the answer (below) as correct. Commented Dec 2, 2017 at 21:32
  • I added the edit before the answer below was posted. The first comment solved the problem for me and as far as I know you cannot mark a comment as correct Commented Dec 2, 2017 at 22:57

1 Answer 1

1

Here, we have

x = array([[ 1.],[ 2.],[ 3.],[ 4.],[ 5.]])
x.T = array([[ 1.,  2.,  3.,  4.,  5.]])

Now you are trying to add two matrices of different dimensions (1 X 5) and (5 X 1).

The way numpy handles this is by copying elements in each row of 1st matrix across its columns to match a number of columns of 2nd matrix and copying elements in each column of 2nd matrix across its rows to match no. of rows of 1st matrix. This gives you 2 5 X 5 matrix which can be added together.

The element wise addition is done as

array([[ 1., 1., 1., 1., 1.],[ 2., 2., 2., 2., 2.,],[ 3., 3., 3., 3., 3.,],[4., 4., 4., 4., 4.],[ 5., 5., 5., 5., 5.,]]) + array([[ 1.,  2.,  3.,  4.,  5.],[ 1.,  2.,  3.,  4.,  5.],[ 1.,  2.,  3.,  4.,  5.],[ 1.,  2.,  3.,  4.,  5.],[ 1.,  2.,  3.,  4.,  5.]])

which produces the result

array([[  2.,   3.,   4.,   5.,   6.],
   [  3.,   4.,   5.,   6.,   7.],
   [  4.,   5.,   6.,   7.,   8.],
   [  5.,   6.,   7.,   8.,   9.],
   [  6.,   7.,   8.,   9.,  10.]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.