How to randomize all the items in a matrix in python

133 Views Asked by At

I'm trying to create a function that accepts a matrix and assigns random variables to each item of said matrix using python.

It seems rather simple but I can't seem to get it to work. The two closest tries Ive done were:

def MatrixRandomize(v):
    for rows in v:
        for columns in rows:
            columns = random.random()

and

def MatrixRandomize(v):
    for rows in v:
        for columns in rows:
            rows[columns] = random.random()

For a 3*3 matrix initially full of 0's the first function gives me this:

[[0, 0, 0], [0, 0, 0], [0, 0, 0]]

and the second give me this:

[[0.5405554380526916, 0, 0], [0.1376271091010769, 0, 0], [0.5223432054353907, 0, 0]]

From my understanding I would think the 2nd function should work. I've seen that there are other ways to solve this problem like using numpy but I can't understand the logic behind this not working.

Can anyone spot the mistake in my code?.

2

There are 2 best solutions below

0
On BEST ANSWER

That is not quite how Python works. When you write

for columns in rows:

then, within each iteration, the name columns is bound in a namespace to an object. If you write in the body

    columns = random.random()

then it simply binds it to a different object - it does not alter anything in the original matrix.


In order to actually change the values of the matrix, you need to change its actual values. You didn't specify which matrix library you're using, but presumably something similar to this will work:

for i in range(len(v.num_rows)):
    for j in range(len(v.num_cols)):
        v[i][j] = random.random()

If you're using numpy, refer to the numpy.random module for more efficient alternatives:

import numpy as np

def MatrixRandomize(v):
    np.copyto(v, np.random.random(v.shape))

v = np.zeros((2, 3))
MatrixRandomize(v)
>>> v
array([[ 0.19700515,  0.82674963,  0.04401973],
     [ 0.03512609,  0.1849178 ,  0.40644165]])
0
On

I finally understood what was wrong.

The right way I was thinking of doing it was:

def MatrixRandomize(v):
    for rows in v:
        for columns in range(len(rows)):
            rows[columns] = random.random()

But now I understand the missing link in my logic. Thanks!