Create valid unique variable name(s) from str.
If str is a cellstr, then a unique variable is created for each cell in str.
genvarname ({"foo", "foo"}) ⇒ { [1,1] = foo [1,2] = foo1 }
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).
x = 3.141; genvarname ("x", who ()) ⇒ x1
Note that the result is a char array or cell array of strings, not the
variables themselves. To define a variable, eval()
can be used.
The following trivial example sets x
to 42
.
name = genvarname ("x"); eval ([name " = 42"]); ⇒ x = 42
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
will replace any sequence of disallowed characters with
an underscore. Also, variables may not begin with a digit; in this case
an ‘x’ 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 ensure 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
exclusions if necessary.
See also: isvarname, iskeyword, exist, who, tempname, eval.
Package: octave