Search code examples
pythonarraysmatrixdimensions

making matrices that start from 0 to n


I was wondering how could one make a 4*4 matrix that starts from 0 to 16?

I don't want to do it manually. imagine doing it for a 10*10 matrix that starts from 0 to 100. lol. there has to be some way to do it more efficiently than to do it manually.


Solution

  • This is easiest to do using numpy. Try the following.

    import numpy as np
    print(np.reshape(np.arange(16),(4,-1)))
    

    The result:

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

    If you instead want the numbers to go from 1 to 16, you could simply add 1, as in

    1 + np.reshape(np.arange(16),(4,-1))