Search code examples
shellmatrixnumberstext-processing

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

  • $ 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