ktan
ktan

Reputation: 129

More efficient way to write this numpy code

Hi I'd like to create a 10 x 5 matrix with the first column filled with 1 to 10 and the subsequent columns filled with 2, 3, 4 and 5 times the values of the first column.

I've made things work with the following code, but is there a shorter way to do this?

import numpy as np
mat = np.zeros([10,5])
mat[:,0] = np.arange(1,11)
mat[:,1] = np.dot(mat[:,0],2)
mat[:,2] = np.dot(mat[:,0],3)
mat[:,3] = np.dot(mat[:,0],4)
mat[:,4] = np.dot(mat[:,0],5)

Upvotes: 0

Views: 71

Answers (3)

kabanus
kabanus

Reputation: 25895

This is exactly what builtin numpy outer does:

>>> np.outer(np.arange(1, 11), np.arange(1, 6))
array([[ 1,  2,  3,  4,  5],
       [ 2,  4,  6,  8, 10],
       [ 3,  6,  9, 12, 15],
       [ 4,  8, 12, 16, 20],
       [ 5, 10, 15, 20, 25],
       [ 6, 12, 18, 24, 30],
       [ 7, 14, 21, 28, 35],
       [ 8, 16, 24, 32, 40],
       [ 9, 18, 27, 36, 45],
       [10, 20, 30, 40, 50]])

Upvotes: 1

lenik
lenik

Reputation: 23498

This works for me:

>>> np.array([np.array([1,2,3,4,5]) * i for i in range(1,11)])
array([[ 1,  2,  3,  4,  5],
       [ 2,  4,  6,  8, 10],
       [ 3,  6,  9, 12, 15],
       [ 4,  8, 12, 16, 20],
       [ 5, 10, 15, 20, 25],
       [ 6, 12, 18, 24, 30],
       [ 7, 14, 21, 28, 35],
       [ 8, 16, 24, 32, 40],
       [ 9, 18, 27, 36, 45],
       [10, 20, 30, 40, 50]])

Upvotes: 1

A. Maman
A. Maman

Reputation: 972

I think you can achieve this by outer product.

Try:

import numpy as np

a = np.arange(1, 11).reshape(-1, 1)    # column vector (1,2,3,...,10)
b = np.arange(1, 6).reshape(1, -1)     # row vector (1,2,3,...,5)
np.matmul(a, b)                        # matrix of entries of multiplication of the indices (1-based indices)

or the one-liner:

np.arange(1, 11).reshape(-1, 1) * np.arange(1, 6).reshape(1, -1)

Upvotes: 1

Related Questions