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

cmplx96
  • 1,541
  • 8
  • 34
  • 48
  • 5
    Please read up on `broadcasting` - https://docs.scipy.org/doc/numpy-1.13.0/user/basics.broadcasting.html. – Divakar Dec 02 '17 at 19:43
  • Possible duplicate of [Numpy array broadcasting rules](https://stackoverflow.com/questions/11178179/numpy-array-broadcasting-rules) –  Dec 02 '17 at 20:53
  • Instead of adding "Edit: OK thanks, got it" to your question, please mark the answer (below) as correct. – Nils Werner Dec 02 '17 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 – cmplx96 Dec 02 '17 at 22:57

1 Answers1

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.]])
Sarit Adhikari
  • 1,344
  • 2
  • 16
  • 28