1

Let's suppose i have this array:

import numpy as np
x = np.arange(4)

array([0, 1, 2, 3])

I want to write a very basic formula which will generate from x this array:

array([[0, 1, 2, 3],
       [1, 2, 3, 4],
       [2, 3, 4, 5],
       [3, 4, 5, 6]])

What is the shortest way to do that with python and numpy ?

Thanks

Bob5421
  • 7,757
  • 14
  • 81
  • 175

2 Answers2

1

The easiest way I can think of is to use numpy broadcasting.

x[:,None]+x
Out[87]: 
array([[0, 1, 2, 3],
       [1, 2, 3, 4],
       [2, 3, 4, 5],
       [3, 4, 5, 6]])
Allen Qin
  • 19,507
  • 8
  • 51
  • 67
0

This should do what you want (note that I have introduced a different number of rows (5) than of columns (4) to make a clear distinction):

import numpy as np

A = np.tile(np.arange(4).reshape(1,4),(5,1))+np.tile(np.arange(5).reshape(5,1),(1,4))

print(A)

A break-down of steps:

  1. np.tile(np.arange(4).reshape(1,4),(5,1)) creates a (5,4) matrix with entries 0,1,2,3 in each row:

    [[0 1 2 3]
     [0 1 2 3]
     [0 1 2 3]
     [0 1 2 3]
     [0 1 2 3]]
    
  2. np.tile(np.arange(5).reshape(5,1),(1,4)) creates a (5,4) matrix with 0,1,2,3,4 in each column:

    [[0 0 0 0]
     [1 1 1 1]
     [2 2 2 2]
     [3 3 3 3]
     [4 4 4 4]]
    
  3. The sum of the two results in what you want:

    [[0 1 2 3]
     [1 2 3 4]
     [2 3 4 5]
     [3 4 5 6]
     [4 5 6 7]]
    
Tom de Geus
  • 5,625
  • 2
  • 33
  • 77