(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
- #!/usr/bin/env python
- import sys, random, time
- if len(sys.argv)!=5:
- print "usage: ./matr-gen.py #rows #cols #smallest #largest";
- print "smallest and #largest should both be integers";
- sys.exit(1)
- rows=int(sys.argv[1])
- cols=int(sys.argv[2])
- smallest=int(sys.argv[3])
- largest=int(sys.argv[4])
- if rows<=0 or cols <=0:
- print "#rows and #cols must be positive integers"
- sys.exit(1)
- for i in range(rows):
- #print i,
- random.seed(i+time.time())
- for j in range(cols):
- ele=random.randint(smallest,largest)
- print ele,
- 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
Recent Comments