File Exchange

image thumbnail

Random String Utility

version 1.0 (1.68 KB) by

Generate a random string. Specify length and type of characters.



View License

RANDOM_STRING - Generate a random string

When a name is needed but none is provided, never fear
RANDOM_STRING is here! As configured returns a random
set of upper case letters (default of 10 long)

value - Length of the random string to generate
default - 10
type - int
value - Type of characters to include.
1 = A-Z, 2 = a-z, 3=letters/#'s/special chars
default - 1
type - int

value - The generated random string
type - str

my_str = random_string(); % 10 upper case letters
my_str = random_string(15); % 5 upper case letters
my_str = random_string(8, 3); % 8 ascii characters

Comments and Ratings (2)

Dan Couture

Thanks for the suggestions Jan. I understand the confusion with the "@" symbol in the comments. It's a general comment format I've used in PHP and Python.

I concur that this utility was not designed to guarantee uniqueness between calls, but to provide a simple way to generate a string in a desired format. If your implementation requires uniqueness, options include either increase the length to an acceptable limited risk or check the return of the function for a match to other strings in your use case.

MD5 and tempname have their own drawbacks but can definitely be used if you do not need the extended functionality.
Limitations to MD5:
*Does not guarantee uniqueness
*Is a fixed length
*Limited to characters 0-9,a-f

Limitations to tempname:
*Also does not guarantee uniqueness
*Is designed for random file names so does not give you as much flexibility with special characters if needed.

Jan Simon

Jan Simon (view profile)

The term "@length" means the function handle of the length() function in Matlab. Therefore the @ characters in the help section are confusing only.
There is a real chance that a 10 character uppercase string is not unique. It is very common, that non-unique names mean a bug in a program and using this function would be a cause of random (means not reproducible) bugs.
A better idea could be the MD5 of the current time or Matlab's tempname function.

MATLAB Release
MATLAB 7.4 (R2007a)
Tags Add Tags

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video