Search code examples
pythonarraysnumpysplice

Randomizing Array Values


I have a 4x4 array.

Initially the values are all set to 0, however I want to change innermost 2x2 values to a random float.

 a = np.zeros((4,4))
 print(a)
 a[1:3,1:3] = random.uniform(-1,1)
 print(a)

Creates an output:

 [[0.         0.         0.         0.        ]
  [0.         0.66529858 0.66529858 0.        ]
  [0.         0.66529858 0.66529858 0.        ]
  [0.         0.         0.         0.        ]]

When the desired outcome would be:

 [[0.         0.         0.         0.        ]
  [0.         0.random0  0.random1 0.        ]
  [0.         0.random2  0.random3 0.        ]
  [0.         0.         0.         0.        ]]

Solution

  • You need to use the size argument to generate a 2 by 2 random matrix:

    a[1:3,1:3] = random.uniform(-1,1,size=(2,2))