Search code examples
pythonfunctionnumpymatrixnumpy-random

How to randomize all the items in a matrix in python


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?.


Solution

  • 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]])