I want to create a string with random length and random characters, only [a-z][A-Z] and numbers. Is there something built in?
Thanks in advance.
I want to create a string with random length and random characters, only [a-z][A-Z] and numbers. Is there something built in?
Thanks in advance.
There isn't much to add to the answers of @Phonon and @dantswain, except that the range of [a-Z]
,[A-Z]
can be generated in less painful way, and randi
can be used to create integer random values.
symbols = ['a':'z' 'A':'Z' '0':'9'];
MAX_ST_LENGTH = 50;
stLength = randi(MAX_ST_LENGTH);
nums = randi(numel(symbols),[1 stLength]);
st = symbols (nums);
This should work
s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; %find number of random characters to choose from numRands = length(s); %specify length of random string to generate sLength = 50; %generate random string randString = s( ceil(rand(1,sLength)*numRands) )
I started to write this before I realized you wanted [A-Z][a-z] and [0-9]. For that, @Phonon's answer is good.
Just as an alternative, this will generate random ASCII characters in the full range of readable characters from space (32) to tilde (126):
length = 10;
random_string = char(floor(94*rand(1, length)) + 32);
Have you tried the built-in function tempname? For example, these two lines will give you a randon string in rand_string:
temp_name = tempname
[temp1, rand_string] = fileparts(temp_name)
Please note that rand_string will also contain underscore character "_".