Home > Coding > (python) Generate a random matrix

(python) Generate a random matrix

March 3rd, 2011

I have a demand: generate a matrix of “a” rows and “b” columns. Each element is a random integer, and I want to specify a range for these random integers. Here is the code in python:

(Caution: you can download this program and it should work. However, if it doesn’t work, you may need to create a new file and copy the code into that new file. This is because the webserver introduced different “\n” characters.)

Download: matr-gen.py
  1. #!/usr/bin/env python
  2.  
  3. import sys, random, time
  4.  
  5. if len(sys.argv)!=5:
  6.     print "usage: ./matr-gen.py #rows #cols #smallest #largest";
  7.     print "smallest and #largest should both be integers";
  8.     sys.exit(1)
  9.  
  10. rows=int(sys.argv[1])
  11. cols=int(sys.argv[2])
  12. smallest=int(sys.argv[3])
  13. largest=int(sys.argv[4])
  14.  
  15. if rows<=0 or cols <=0:
  16.     print "#rows and #cols must be positive integers"
  17.     sys.exit(1)
  18.  
  19. for i in range(rows):
  20.     #print i,
  21.     random.seed(i+time.time())
  22.     for j in range(cols):
  23.         ele=random.randint(smallest,largest)
  24.         print ele,
  25.     print ;

If you run it with arguments like this: “./matr-gen.py 9 9 50 99″. The results might be like:

76 93 98 89 62 65 99 99 95 82
88 82 81 50 98 51 80 95 91 77
99 57 66 69 53 58 69 75 76 50
73 57 83 80 53 92 67 60 56 93
79 84 89 97 58 78 84 65 64 87
68 99 74 56 89 81 54 96 60 61
81 75 76 54 82 99 83 84 51 60
63 83 74 50 94 97 88 58 63 56
90 82 75 74 58 66 81 54 99 80
63 50 68 87 53 66 64 59 95 52

Coding

  1. No comments yet.
  1. No trackbacks yet.