By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,814 Members | 1,050 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,814 IT Pros & Developers. It's quick & easy.

random numbers in a matrix in python

P: 6
I'm still new to python, so I would like to know how do I get random numbers in my matrix; more specific, what is the commands for getting a random matrix.
THANX for the help guys
Feb 22 '09 #1
Share this Question
Share on Google+
5 Replies


boxfish
Expert 100+
P: 469
What kind of random numbers do you want? Do you want to include non integers? How big do you want the numbers to get? You might want to use the randrange function from the random module.
Feb 22 '09 #2

P: 6
its not a big matrix, say 7-by-7, the thing is I already have a zero-matrix, its getting the random numbers in. My range is from 0 to 6, for the random numbers.
Feb 22 '09 #3

P: 6
I already have a zero-matrix, 7-by-7, so I want to now get random numbers in, any natural numbers from 1-6
Feb 22 '09 #4

boxfish
Expert 100+
P: 469
random.randrange(x, y) returns a random integer in the range [x, y), so random.randrange(1, 7) will return a number from one to six. The first parameter is optional and defaults to zero. You'll need to import the random module.
Expand|Select|Wrap|Line Numbers
  1. import random
  2. print random.randrange(1, 7)
I hope this helps.
Feb 23 '09 #5

bvdet
Expert Mod 2.5K+
P: 2,851
boxfish's suggestion is a good way to do it. I have a Matrix object with a __setitem__() overload.
Expand|Select|Wrap|Line Numbers
  1. m0 = Matrix(7,7)
  2.  
  3. import random
  4.  
  5. for i in range(m0.rows):
  6.     for j in range(m0.cols):
  7.         m0[i,j] = random.randrange(1,7)
Expand|Select|Wrap|Line Numbers
  1. >>> print m0
  2. Row 0 = [1, 2, 5, 1, 4, 5, 1]
  3. Row 1 = [6, 6, 4, 2, 5, 3, 6]
  4. Row 2 = [2, 2, 4, 4, 1, 1, 5]
  5. Row 3 = [1, 4, 5, 3, 4, 3, 4]
  6. Row 4 = [3, 6, 6, 5, 5, 6, 4]
  7. Row 5 = [4, 3, 6, 4, 1, 5, 2]
  8. Row 6 = [4, 6, 5, 2, 4, 4, 4]
  9. >>> 
Feb 23 '09 #6

Post your reply

Sign in to post your reply or Sign up for a free account.