'How can I generate a 2D matrix of natural numbers wth zero in ascending order in shell script or another programming language?

I need to generate matrices of natural numbers in ascending order with zero (0), but they are very large ones and it will be hard to write them by hand.

What I want is to generate matrices like this:

0   1   2   3
4   5   6   7
8   9   10  11
12  13  14  15

How can I do that in shell script or another programming language.



Solution 1:[1]

$ seq 0 15 | xargs -n4
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15

Use column for alignment:

$ seq 0 15 | xargs -n4 | column -t
0   1   2   3
4   5   6   7
8   9   10  11
12  13  14  15

Use with variable:

$ n=8 && seq 0 $((n*n-1)) | xargs -n$n
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 30 31
32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47
48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63

Solution 2:[2]

In python:

print('\n'.join([' '.join([str(x*n+y) for y in range(0,k)]) for x in range(0,n)]))

Well, you might want to use tabulate or something to keep it aligned..

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 eyal0931