How can I generate a random string in Matlab?

2020-02-09 08:11发布

问题:

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.

回答1:

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);


回答2:

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) )


回答3:

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);


回答4:

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 "_".



标签: matlab random