443,814 Members | 1,050 Online
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
5 Replies

 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

 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 import random print random.randrange(1, 7) I hope this helps. Feb 23 '09 #5

 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 m0 = Matrix(7,7)   import random   for i in range(m0.rows):     for j in range(m0.cols):         m0[i,j] = random.randrange(1,7) Expand|Select|Wrap|Line Numbers >>> print m0 Row 0 = [1, 2, 5, 1, 4, 5, 1] Row 1 = [6, 6, 4, 2, 5, 3, 6] Row 2 = [2, 2, 4, 4, 1, 1, 5] Row 3 = [1, 4, 5, 3, 4, 3, 4] Row 4 = [3, 6, 6, 5, 5, 6, 4] Row 5 = [4, 3, 6, 4, 1, 5, 2] Row 6 = [4, 6, 5, 2, 4, 4, 4] >>>  Feb 23 '09 #6