Search code examples
pythonnumpyarray-broadcastingnumpy-random

Generating random numbers around a set of coordinates without for loop


I have a set of coordinate means (3D) and a set of standard deviations (3D) accompying them like this:

means = [[x1, y1, z1],
         [x2, y2, z2],
         ...
         [xn, yn, zn]]

stds = [[sx1, sy1, sz1],
        [sx2, sy2, sz2],
         ...
        [sxn, syn, szn]]

so the problem is N x 3

I am looking to generate 1000 coordinate sample sets (N x 3 x 1000) randomly using np.random.normal(). Currently I generate the samples using a for loop:

for i in range(0,1000):
  samples = np.random.normal(means, stds)

But I have the feeling I can lose the for loop and let numpy do it faster and in one call, anybody know how I should code that?


Solution

  • or alternatively use the size argument:

    import numpy as np
    
    means = [ [0, 0, 0], [1, 1, 1] ]
    std = [ [1, 1, 1], [1, 1, 1] ]
    
    #100 samples
    print(np.random.normal(means, std, size = (100, len(means), 3)))