MATLAB: How to randomly select words from a column without replacement

randomreplacement

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.

Best Answer

You can get the random numbers in advance of your loop, then simply use them. It's also very bad practice to redefine your loop iterator, n, inside your loop. See improved code below:
myarray = {'John' 'likes' 'cats'; 'Alex' 'hates' 'rabbits'; 'Lucy' 'loves' 'frogs'};
Column1 = myarray(:,1);
Column2 = myarray(:,2);
Column3 = myarray(:,3);
% Get random numbers, not repeating.
r1 = randperm(3);
r2 = randperm(3);
r3 = randperm(3);
for n = 1:3
Word1 = Column1{r1(n)};
Word2 = Column2{r2(n)};
Word3 = Column3{r3(n)};
% n = [Word1 Word2 Word3] % DON'T DO THIS!
fprintf('%s %s %s\n', Word1, Word2, Word3);
end