Skip to content Skip to sidebar Skip to footer

Python Oneline To Create Matrix Of Given Order

I am looking for python oneliner that will create matrix with the given order and fill values from 1 to n. n = r X c I achieved till this, Matrix1 = [[x+1 for x in range(rowCount)

Solution 1:

No, the correct way is without loop (and in one line):

import numpy as np

rowCount = 2
colCount = 5

np.array(range(1, 1+rowCount*colCount)).reshape(rowCount,colCount)

#array([[ 1,  2,  3,  4,  5],
#       [ 6,  7,  8,  9, 10]])

Solution 2:

>>> matrix1 = [[1+x+y*rowCount for x in range(rowCount)] for y in range(columnCount)]
>>> matrix1
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Solution 3:

You use the same variable for your two loops. Try this :

matrix1 = [[y*rowCount + x + 1 for x in range(rowCount)] for y in range(columnCount)]
print matrix1

Solution 4:

Given c (column count), n, here's what I came up with:

[range(0, n)[cx:cx+c] for cx in range(0, n, c)]

Result:

In [16]: n = 9

In [17]: c = 3

In [18]: [range(0, n)[cx:cx+c] for cx in range(0, n, c)]
Out[18]: [[0, 1, 2], [3, 4, 5], [6, 7, 8]]

EDIT: More examples for non square matrices: (mod is a function i created to quickly change r and c values, and calculate n from them)

In [23]: mod(8, 2)  # 8 rows, 2 columns

In [24]: [range(0, n)[cx:cx+c] for cx in range(0, n, c)]
Out[24]: [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9], [10, 11], [12, 13], [14, 15]]

In [25]: mod(3, 6)  # 3 rows, 6 columns

In [26]: [range(0, n)[cx:cx+c] for cx in range(0, n, c)]
Out[26]: [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17]]

In [27]: mod(10, 3)  # 10 rows, 3 columns

In [28]: [range(0, n)[cx:cx+c] for cx in range(0, n, c)]
Out[28]: 
[[0, 1, 2],
 [3, 4, 5],
 [6, 7, 8],
 [9, 10, 11],
 [12, 13, 14],
 [15, 16, 17],
 [18, 19, 20],
 [21, 22, 23],
 [24, 25, 26],
 [27, 28, 29]]

It works for them too.


Post a Comment for "Python Oneline To Create Matrix Of Given Order"