Generating random numbers around a set of coordinates without for loop

433 Views Asked by At

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?

2

There are 2 best solutions below

3
On BEST ANSWER

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)))
0
On

You can repeat your means and stds arrays 1000 times, and then call np.random.normal() once.

means = [[0, 0, 0],
         [1, 1, 1]]

stds = [[1, 1, 1],
        [2, 2, 2]]

means = numpy.array(means) * numpy.ones(1000)[:, None, None]
stds = numpy.array(stds) * numpy.ones(1000)[:, None, None]

samples = numpy.random.normal(means, stds)