how can I take a random sample from a cell array?

2019-08-12 08:51发布

问题:

I have a cell array in matlab and I need to take a random sample, however the randsample() function in matlab appears not to work on cell arrays. I can generate random numbers using randi() which is fine, however I want only unique numbers.

Is there a function that can be used to randomly sample from a cell array, or can anyone show me how to generate unique numbers using randi()?

Thanks very much.

回答1:

You can use the randperm function which generates a random permutation without repeat of the numbers.

For example P = randperm(N,K) gives K unique, non repeating numbers between 1 and N

randperm(10,5) gives me:

9     2     1     6     5

randperm(10,10) gives me:

7     9     4     8     2     3     6     5     1    10

Lets say you have a cell array

C = {'only','mad','dogs','and','englishmen','go','out','in','the','midday','sun'}

Then you could generate a set of random phrases without repeating tokens like this

output=[];
for i=1:5
    output = [output;sprintf('%s ',C{randperm(length(C))})];
end

which gives me an output like the following

out only dogs in mad englishmen sun go and midday the 
in and the midday sun only englishmen out go dogs mad 
out midday go in dogs and only englishmen the mad sun 
the sun out mad midday englishmen go only and dogs in 
midday mad sun out dogs in and go englishmen the only