Hi All,
I have been attempting to generate a singular random word, from a set of words in a txt file labelled: dictionary.txt
So far, my code is as follows:
Dictionary="dictionary.txt";
Random=randperm(length("dictionary.txt"),1);
randword = Dictionary{Random}
However, when i run the code, it returns:
randword =
'dictionary.txt'
How can i make it so that the code displays a random word within the dictionary.txt file, rather than the file name?
Kind Regards,
Smoxk x

 채택된 답변

KSSV
KSSV 2022년 4월 12일

1 개 추천

Dictionary='dictionary.txt';
n = 5 ; % letters to pick from the string
Random=randperm(length(Dictionary),5);
randword = Dictionary(Random)
randword = 'ynx.o'

댓글 수: 7

Smoxk x
Smoxk x 2022년 4월 12일
편집: Smoxk x 2022년 4월 12일
Hey @KSSV,
Thanks so much for the response! :)
The 'dictionary.txt' file contains words such as "dog" "snake" "water". How would i edit the code to display a random word thats already within the 'dictionary.txt' file such as "fish"?
Could i make the code for random word generation into a function maybe? I have to use it in multiple segments of my code.
Kind Regards,
Luke
KSSV
KSSV 2022년 4월 12일
Attach your file.
Smoxk x
Smoxk x 2022년 4월 12일
편집: Smoxk x 2022년 4월 12일
Ok, above is the attached 'dictionary.txt'
file = 'dictionary.txt' ; % file name
S = importdata(file) ; % import the data
N = numel(S) ; % get the length of the file
idx = randperm(N,1) ; % get random number
S(idx)
Smoxk x
Smoxk x 2022년 4월 12일
@KSSV Thanks so much! I really appreciate the time and effort you took to assist me! Have a great day!
Smoxk x
Smoxk x 2022년 4월 12일
편집: Smoxk x 2022년 4월 12일
Hey @KSSV,
How would i go about making the below code into a function?
file = 'dictionary.txt'; % file name
import = importdata(file); % import the data
Num= numel(import); % get the length of the file
idx = randperm(Num, 1); % get random number
OriginalWord=import(idx);
function OriginalWord = myfunction(filename,n)
% file name - nme of the file
% n - number of random letters needed from the file
import = importdata(file); % import the data
Num= numel(import); % get the length of the file
idx = randperm(Num, n); % get random number
OriginalWord=import(idx);
end

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

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Random Number Generation에 대해 자세히 알아보기

질문:

2022년 4월 12일

댓글:

2022년 4월 13일

Community Treasure Hunt

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

Start Hunting!

Translated by