フィルターのクリア

Printing a sentence using one random element from each cell array?

2 ビュー (過去 30 日間)
Nora
Nora 2013 年 10 月 20 日
コメント済み: Walter Roberson 2013 年 10 月 20 日
Question: Write a script that will initalize cell arrays and print sentences using one random element from each cell array (ex. 'Harry loves cats').
What I have so far is this:
names = {'Harry', 'Sarah', 'Sue'};
verbs = {'loves', 'likes'};
nouns = {'cats', 'dogs', 'zebras'};
for i=1:length(names)
fprintf('%s\n',i,names{i})
end
However, this only gives me the 'names' array.
How can I print a sentence using one random element from each cell array?

採用された回答

Walter Roberson
Walter Roberson 2013 年 10 月 20 日
Hint:
names{randi(length(names))}

その他の回答 (1 件)

Image Analyst
Image Analyst 2013 年 10 月 20 日
編集済み: Image Analyst 2013 年 10 月 20 日
Homework Hint: If your cells start out as sentences like 'Harry loves cats', use regexp() or strtok() to get the individual words, or simpler and better yet, use allwords: http://www.mathworks.com/matlabcentral/fileexchange/27184-allwords
But if your words are already extracted out like you showed in your test code, then just get 3 random integers using randi() and print all of them, not just names like you did
fprintf('%s %s %s\n', names{rand1}, verbs{rand2}, nouns{rand3});
  2 件のコメント
Nora
Nora 2013 年 10 月 20 日
The fprintf above doesn't work. MATLAB is saying that rand1 is unidentified?
Walter Roberson
Walter Roberson 2013 年 10 月 20 日
Did you get three random integers using randi() ?

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by