How can I randomly select words from a column without replacement?
Show older comments
I'd like to use a cell array to make 3 random sentences with no repeated words (using MATLAB 2018b):
myarray = {'John' 'likes' 'cats'; 'Alex' 'hates' 'rabbits'; 'Lucy' 'loves' 'frogs'};
Column1 = myarray(:,1);
Column2 = myarray(:,2);
Column3 = myarray(:,3);
for n = 1:3
Word1 = Column1(randperm(length(Column1),1));
Word2 = Column2(randperm(length(Column2),1));
Word3 = Column3(randperm(length(Column3),1));
n = [Word1 Word2 Word3]
end
but I often get repeated words, like this:
{'John'} {'loves'} {'rabbits'}
{'John'} {'likes'} {'rabbits'}
{'Lucy'} {'likes'} {'frogs'}
How can I make it so that all words are used and no words are repeated? Thanks in advance.
Accepted Answer
More Answers (1)
Guillaume
on 8 Nov 2018
Use randperm properly. randperm(x, 1) is the same as randi(x) and of course if you do that 3 times, there's no guarantee you don't get repetition. randperm(x, 3) guarantees you to pick 3 different random numbers. And since your array has only 3 rows, randperm(x) would work just as well:
p = zeros(size(myarray));
for col = 1:size(myarray, 2)
p(:, col) = randperm(size(myarray, 2)) + (col-1) * size(myarray, 1);
end
result = myarray(p)
Categories
Find more on Language Support in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!