2

I have this line of code in a MATLAB program:

x(:,i) = gamrnd(a(i),1,dim,1)

I was wondering in what way I could write this same line in Python. I think the equivalent statement is:

gamma.rvs(a, size=1000) 

However, this keeps giving me an Index Error.

Here is my full code for this part:

x = np.array([])
for i in range(N-1):
    # generates dim random variables
    x[:, i] = gamma.rvs(a[i], dim-1)    # generates dim random variables
                                            # with gamma distribution

Thanks for the help!

A.Torres
  • 413
  • 1
  • 6
  • 16

1 Answers1

0

You initialized x = np.array([]) and then tried accessing x[:, 0], which doesn't exist, hence the Index Error. You'll want to append instead:

x = np.array([])
for i in range(N-1):
    np.append(x, gamma.rvs(a[i], dim - 1))

The documentation for np.append can be found here.

Zain Patel
  • 983
  • 5
  • 14
  • `np.append` is extremely inefficient. Also, this will produce a flat array rather than the shape the questioner is looking for. – user2357112 Aug 18 '18 at 00:20