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!

2
  • Please post the actual error you're seeing and when it occurs. gamma.rvs(a, size=1000) should just work. Commented Aug 17, 2018 at 21:55
  • 1
    The problem is x[:, i]. That index doesn't exist. Commented Aug 17, 2018 at 22:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

np.append is extremely inefficient. Also, this will produce a flat array rather than the shape the questioner is looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.