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

你。 提交于 2019-12-11 07:46:49

问题


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 


来源:https://stackoverflow.com/questions/18262196/how-can-i-take-a-random-sample-from-a-cell-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!