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

5
  • 1
    Not sure it's a dupe of that, @Divakar. Looks like he may want x[None, :] + x[:, None] Which is probably a dupe of something else, simple as it is. Commented May 10, 2017 at 9:26
  • @DanielF Using a stepsize=1 solves, it, doesn't it? Commented May 10, 2017 at 9:27
  • Not from the original x array he specified. There are no 4,5,6 elements to stride to using stride_tricks Commented May 10, 2017 at 9:29
  • @DanielF Ah yes, thanks! Reopened. Commented May 10, 2017 at 9:34
  • @Bob5421 What's the criteria of adding a dimension here? Commented May 10, 2017 at 9:35

2 Answers 2

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]])
Sign up to request clarification or add additional context in comments.

Comments

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]]
    

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.