generate random upper string in function

조회 수: 9 (최근 30일)
david Chan
david Chan 2014년 11월 17일
댓글: david Chan 2014년 11월 18일
I tried to generate the same length of upper string as the input argument. For example, if I put wordscramble('abcd'), the length of the function should generate a four length upper string , like 'EFSA'. However, it seems doesnt work for it, is that any error in my codes?
function y = wordscramble(str)
y = str2func(str);
exchange = randperm(length(str));
x = 0;
y='';
for i=1:length(str)
y(i) = str(upper(exchange(i)));
end

채택된 답변

Geoff Hayes
Geoff Hayes 2014년 11월 17일
David - your code, as written, just permutes the four characters of the input string so if your input is abcd you will never get an output of EFSA since E, F, and S are not characters in the input string. If that is what you want, then your above code can be simplified to
function y = wordscramble(str)
exchange = randperm(length(str));
y = upper(str(exchange));
Note how we don't need a for loop and that upper is applied to the input string characters and not the numbers in exchange.
If you wish to generate a random string of any four uppercase characters, then you could create an array of all characters (or their ASCII equivalent) and just randomly select four characters from that array. Something like
function y = wordscramble2(str)
aToZUpper = 65:1:90;
exchange = randperm(length(aToZUpper),length(str));
y = char(aToZUpper(exchange));
In the above, we create an array of 26 integers, using the ASCII decimal equivalent for each of the upper case characters A (65), B (66), ...., Z (90). We then randomly choose x characters where x is the length of our input string, and return the result.
  댓글 수: 1
david Chan
david Chan 2014년 11월 18일
it uses for-loop because it wanst go thorugh the function. But now, it works, I add '' like wordscramble('word') instead of wordscramble(). thanks for your answer by the way

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by