random letter bother upper & lower case

8 ビュー (過去 30 日間)
Micheal McDonagh
Micheal McDonagh 2021 年 6 月 24 日
回答済み: Steven Lord 2021 年 6 月 24 日
How do I create a random letter both upper or lower case?
I know how do to do it for a number
number = randi([1,50])
% gives me a random number in the range of 1 to 50
Can I use something similer to create a random single upper or lower case letter? My code below is fine, but I have the input function which allows me to maunally pick a letter.
But I dont want to manually pick a letter, how do I get a random upper or lower letter without manually picking one?
clc, clear all, close all
letter = input('Enter a letter: ', 's');
if letter == 'x'
disp('Hellp')
elseif letter == 'y' || letter == 'Y'
disp('Yes')
elseif letter == 'Q'
disp('Quit')
else
disp('Error')
end

採用された回答

millercommamatt
millercommamatt 2021 年 6 月 24 日
This is a fun puzzle. Upper-case letters run of 65-90 in an ASCII table and lower-case runs from 97 to 122. You can use char to convert from the number to the equivalent ascii character.
randomletter = char(randi([65,95]) + randi([0,1]).*32);

その他の回答 (1 件)

Steven Lord
Steven Lord 2021 年 6 月 24 日
uppercase = 'A':'Z';
lowercase = 'a':'z';
letters = [uppercase lowercase];
whichLetters = randi(numel(letters), 1, 10)
whichLetters = 1×10
6 1 31 40 43 34 51 26 42 48
randomLetters = letters(whichLetters)
randomLetters = 'FAenqhyZpv'
Elements in whichLetters that are less than or equal to numel(uppercase) are drawn from the uppercase variable and those that are greater are drawn from lowercase. Alternately you could treat letters like a "deck of cards" and shuffle it. This would let you draw letters without replacement. randomLetters as created above could have duplicates.
shuffledOrder = randperm(numel(letters));
shuffledLetters = letters(shuffledOrder)
shuffledLetters = 'JlQjTzVopnsHXOqiLPcewyUGuImBrWakFhADgbYxdvMfNtCSEKRZ'

カテゴリ

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