Reputation: 13
I have
x = np.linspace(0, 1, 6)
y = np.linspace(0, 1, 9)
How can I have a matrix 7x10 from (x,y) but each row becomes from the previous one by adding 1? For example, the first row is
0,1,2,3,4,5,6
the second row
1,2,3,4,5,6,7
and so on
Upvotes: 1
Views: 49
Reputation: 9941
With broadcasting in numpy:
x = np.arange(7)
y = np.arange(10)
x[np.newaxis, :] + y[:, np.newaxis]
Output:
array([[ 0, 1, 2, 3, 4, 5, 6],
[ 1, 2, 3, 4, 5, 6, 7],
[ 2, 3, 4, 5, 6, 7, 8],
[ 3, 4, 5, 6, 7, 8, 9],
[ 4, 5, 6, 7, 8, 9, 10],
[ 5, 6, 7, 8, 9, 10, 11],
[ 6, 7, 8, 9, 10, 11, 12],
[ 7, 8, 9, 10, 11, 12, 13],
[ 8, 9, 10, 11, 12, 13, 14],
[ 9, 10, 11, 12, 13, 14, 15]])
Or the same thing with np.reshape
:
x.reshape(1, -1) + y.reshape(-1, 1)
And here's possibly a little more readable, but significantly less computationally efficient:
m = np.empty((10, 7))
for i in range(10):
for j in range(7):
m[i, j] = i + j
Upvotes: 3