0

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)
1
  • 2
    Use outer multiplication : np.arange(1,11)[:,None]*np.arange(1,6). Commented May 10, 2020 at 14:07

3 Answers 3

1

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

1 Comment

If it answers please mark it as answered by the v under the vote arrows :)
1

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

1 Comment

You can multiply one array by another; that's faster than the list comprehension.
1

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

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.