generate random upper string in function

2 views (last 30 days)
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

Accepted Answer

Geoff Hayes
Geoff Hayes on 17 Nov 2014
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 Comment
david Chan
david Chan on 18 Nov 2014
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

Sign in to comment.

More Answers (0)

Categories

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

Community Treasure Hunt

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

Start Hunting!