Create unique variable(s) from str. If exclusions is given, then the variable(s) will be unique to each other and to exclusions (exclusions may be either a string or a cellstr).
If str is a cellstr, then a unique variable is created for each cell in str.
x = 3.141; genvarname ("x", who ()) x1If wanted is a cell array, genvarname will make sure the returned strings are distinct:
genvarname ({"foo", "foo"}) { [1,1] = foo [1,2] = foo1 }Note that the result is a char array/cell array of strings, not the variables themselves. To define a variable,
eval()
can be used. The following trivial example setsx
to42
.name = genvarname ("x"); eval([name " = 42"]); x = 42Also, this can be useful for creating unique struct field names.
x = struct (); for i = 1:3 x.(genvarname ("a", fieldnames (x))) = i; endfor x = { a = 1 a1 = 2 a2 = 3 }Since variable names may only contain letters, digits and underscores, genvarname replaces any sequence of disallowed characters with an underscore. Also, variables may not begin with a digit; in this case an underscore is added before the variable name.
Variable names beginning and ending with two underscores "__" are valid but they are used internally by octave and should generally be avoided, therefore genvarname will not generate such names.
genvarname will also make sure that returned names do not clash with keywords such as "for" and "if". A number will be appended if necessary. Note, however, that this does not include function names, such as "sin". Such names should be included in avoid if necessary.