Home > database >  How to create a multidimensional matrix in Python
How to create a multidimensional matrix in Python

Time:08-31

I am a beginner in Python. I want to create the matrix below, how should I create it?

[
    [0,1], [0,2], [0,3],
    [1,1], [1,2], [1,3],
    [2,1], [2,2], [2,3],
    [3,1], [3,2], [3,3]
]

I looked up numpy, maybe I'm not looking in the right way, I didn't find any good way.

CodePudding user response:

This is almost what numpy.ndindex is doing, except you want one of the values to start with 1. You can fix it by converting to array and adding 1:

np.array(list(np.ndindex(4,3))) [0,1]

Output:

array([[0, 1],
       [0, 2],
       [0, 3],
       [1, 1],
       [1, 2],
       [1, 3],
       [2, 1],
       [2, 2],
       [2, 3],
       [3, 1],
       [3, 2],
       [3, 3]])

CodePudding user response:

A rather simple list comprehension will generate this data structure. Numpy not required.

[[x, y] for x in range(4) for y in range(1, 4)]

Result:

[[0, 1], [0, 2], [0, 3], 
 [1, 1], [1, 2], [1, 3], 
 [2, 1], [2, 2], [2, 3], 
 [3, 1], [3, 2], [3, 3]]
  • Related