- Read the file word by word.
- Use rand to determine which word to choose.
Random function from a text file?
2 次查看(过去 30 天)
显示 更早的评论
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.
0 个评论
采纳的回答
Jan
2011-12-3
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 个)
the cyclist
2011-12-3
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Import and Export 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!