Random function from a text file?

Basically, I have a text file with a bunch of words on it. I'm not sure how I can use MATLAB to randomly select one word.

 採用された回答

Jan
Jan 2011 年 12 月 3 日

0 投票

  1. Read the file word by word.
  2. Use rand to determine which word to choose.
fid = fopen('FileName.txt', 'r');
if fid < 0, error('Cannot open file.'); end
CC = textscan(fid, '%s');
C = CC{1};
fclose(fid);
index = ceil(rand * numel(C));
chosen = C{index};

1 件のコメント

Chris
Chris 2011 年 12 月 3 日
Nevermind! Thank you.

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

その他の回答 (1 件)

the cyclist
the cyclist 2011 年 12 月 3 日

0 投票

There are many MATLAB functions that can read text from files. One possibility that might work for you is the textscan() function. That will read the file into a cell array. Then, you could randomly select one element of the cell array, perhaps using the randi() command.
>> doc textscan
>> doc randi
Those help files give the detailed syntax, and also point to other functions you might prefer to use.

1 件のコメント

Chris
Chris 2011 年 12 月 3 日
Thank you still!

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

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

タグ

質問済み:

2011 年 12 月 3 日

Community Treasure Hunt

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

Start Hunting!

Translated by