How can I randomly select words from a column without replacement?

조회 수: 7 (최근 30일)
Sarah
Sarah 2018년 11월 8일
댓글: Sarah 2018년 11월 9일
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.

채택된 답변

Image Analyst
Image Analyst 2018년 11월 8일
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
  댓글 수: 1
Sarah
Sarah 2018년 11월 9일
Many thanks for the improved code and the tip to not redefine n inside the loop! I also realized, in working through your suggestion, that I can add an array, S:
myarray = {'John' 'likes' 'cats'; 'Alex' 'hates' 'rabbits'; 'Lucy' 'loves' 'frogs'};
Column1 = myarray(:,1);
Column2 = myarray(:,2);
Column3 = myarray(:,3);
r1 = randperm(3);
r2 = randperm(3);
r3 = randperm(3);
S = {};
for n = 1:3
Word1 = Column1{r1(n)};
Word2 = Column2{r2(n)};
Word3 = Column3{r2(n)};
S(n,:) = {Word1 Word2 Word3};
end
...which gives me a nice output array:
{'John'} {'likes'} {'cats'}
{'John'} {'loves'} {'frogs'}
{'Lucy'} {'likes'} {'cats'}
...which (though I completely neglected to mention this in the original question) is what I ultimately needed.
Anyway, thank you again!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Guillaume
Guillaume 2018년 11월 8일
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)

카테고리

Help CenterFile Exchange에서 Historical Contests에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by