genvarname

Builds valid, unique variable names from text (superseded by matlab.lang.makeValidName).

Category: Programming > Functions

Syntax

v = genvarname(str)

Converts str into a valid variable name.

v = genvarname(str, exclusions)

Also avoids every name in exclusions.

Description

genvarname removes spaces and capitalizes the letter that follows each one, replaces other invalid characters, prefixes x to names that start with a digit or are reserved keywords, and then appends a number when the result collides with an entry of exclusions or with an earlier name in the same call.

It is handy for turning headings or file names into dynamic field names or variables. New code should use matlab.lang.makeValidName and matlab.lang.makeUniqueStrings.

Input arguments

str
Text or cell array of text.
exclusions
Name or cell array of names that must not be returned.

Output arguments

v
Valid name, or a cell array of names when str is a cell array.

Example

Valid and unique names

genvarname('total cost')
genvarname('2nd try')
genvarname('x', {'x', 'x1'})
genvarname({'a', 'a', 'a'})
Output
ans = 'totalCost'
ans = 'x2ndTry'
ans = 'x2'
ans = 1×3 cell

    {'a'}    {'a1'}    {'a2'}

See also

matlab.lang.makeValidName matlab.lang.makeUniqueStrings isvarname iskeyword