Numpy (python) – create a matrix with rows having subsequent values multiplied by the row's number

Question:

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.

Asked By: Mery p.

||

Answers:

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

Answered By: Matt Hall
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.