Home > Back-end >  Numpy (python) - create a matrix with rows having subsequent values multiplied by the row's num
Numpy (python) - create a matrix with rows having subsequent values multiplied by the row's num

Time:12-29

I want to create an n × n matrix with rows having subsequent values multiplied by the row's number. For example for n = 4:

[[0, 1, 2, 3], [0, 2, 4, 6], [0, 3, 6, 9], [0, 4, 8, 12]]

For creating such a matrix, I know the following code can be used:

n, n = 3, 3
K = np.empty(shape=(n, n), dtype=int)
i,j = np.ogrid[:n, :n]
L = i j
print(L)  

I don't know how I can make rows having subsequent values multiplied by the row's number.

CodePudding user response:

You can use the outer product of two vectors to create an array like that. Use np.outer(). For example, for n = 4:

import numpy as np

n = 4
row = np.arange(n)
np.outer(row   1, row)

This produces:

array([[ 0,  1,  2,  3],
       [ 0,  2,  4,  6],
       [ 0,  3,  6,  9],
       [ 0,  4,  8, 12]])

Take a look at row and try different orders of multiplication etc to see what's going on here. As others pointed out in the commets, you should also review your code to see that you're creating n twice and not using K (and in general I'd avoid np.empty() as a beginner because it can lead to unexpected behaviour).

  • Related