2

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
  • randsample() the positions 1:length(cellarray) Commented Aug 15, 2013 at 21:34

1 Answer 1

4

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 
Sign up to request clarification or add additional context in comments.

1 Comment

syntax-wise, you can define a cellarray of strings as: C = {'a','b','c'}, no need for the square brackets.

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.