How can I generate a random string in Matlab?

前端 未结 4 2012
北荒
北荒 2020-12-15 21:56

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.

相关标签:
4条回答
  • 2020-12-15 22:01

    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);
    
    0 讨论(0)
  • 2020-12-15 22:15

    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);
    
    0 讨论(0)
  • 2020-12-15 22:15

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

    0 讨论(0)
  • 2020-12-15 22:16

    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) )
    
    0 讨论(0)
提交回复
热议问题