Home > database >  Replicating MATLAB's `randperm` in NumPy
Replicating MATLAB's `randperm` in NumPy

Time:08-08

I want to replicate MATLAB's randperm() with NumPy.

Currently, to get randperm(n, k) I use np.random.permutation(n)[:k]. The problem is it allocates an array of size n then takes only k entries of it.

Is there a more memory efficient way to directly create the array?

CodePudding user response:

I can recommend you np.random.choice(n, k, replace = False). Yet, I am not sure about memory efficiency. Please refer to docs

CodePudding user response:

Based on @TaQ answer:

np.random.choice(n, k, replace = False)

Is the equivalent to MATLAB's randperm().

Update: I will update his answer as well to mark it.

  • Related