generate random upper string in function
9 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
david Chan
el 17 de Nov. de 2014
Comentada: david Chan
el 18 de Nov. de 2014
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
0 comentarios
Respuesta aceptada
Geoff Hayes
el 17 de Nov. de 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.
Más respuestas (0)
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!