# How to do Randi with letters

조회 수: 8(최근 30일)
Shahar ben ezra 2021년 4월 27일
댓글: Shahar ben ezra 2021년 4월 28일
Is it possible to do the RANDI function with letters?
And you will see an example like this:
X7S7-6S6A-Y555-U75T
for i=1:4
r(i)= randi([1000,9999],1,1);
end
r= num2str(r);
the print look like : Your code is -"4818 3432 2773 8395"
tnx :)

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

### 채택된 답변

Jan 2021년 4월 27일
편집: Jan 2021년 4월 27일
Provide a pool with valid characters and use randi() to determine the random indices:
Pool = ['A':'Z', '0':'9'];
Key = Pool(randi(numel(Pool), 1, 16));
KeyC = cellstr(reshape(Key, 4, []).');
KeyS = strjoin(KeyC, '-');
% Or after creation of [Key]:
KeyS = sprintf('%c%c%c%c-%c%c%c%c-%c%c%c%c-%c%c%c%c', Key); % ugly
##### 댓글 수: 1표시 없음숨기기 없음
Shahar ben ezra 2021년 4월 28일
Thank you very much!

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

### 추가 답변(1개)

Steven Lord 2021년 4월 27일
There's no need for the first loop since randi can create a vector of values.
r = randi([1000,9999],1,4)
r = 1×4
6622 6127 8429 7519
Since you're using a release that includes string I'd use that.
S = string(r)
S = 1×4 string array
"6622" "6127" "8429" "7519"
Now you can join the strings in S together.
code = "Your code is - " + join(S, " ")
code = "Your code is - 6622 6127 8429 7519"
There are other ways you can "do randi with letters" particularly for your first example where you wanted something like "X7S7-6S6A-Y555-U75T"
allowedChars = ['A':'Z' '0':'9'];
whichChars = randi(numel(allowedChars), [4 4]);
selectedChars = allowedChars(whichChars)
selectedChars = 4×4 char array
'XA3C' 'WCML' 'IS22' 'J248'
Now turn each of those vectors into strings and join them as before.
code = "Your code is - " + join(string(selectedChars), " : ")
code = "Your code is - XA3C : WCML : IS22 : J248"
##### 댓글 수: 1표시 없음숨기기 없음
Shahar ben ezra 2021년 4월 28일
Thank you very much!

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

### 범주

Find more on Characters and Strings in Help Center and File Exchange

R2020a

### Community Treasure Hunt

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

Start Hunting!

Translated by