The function you're looking for is matlab.lang.makeValidName
(introduced in R2014a):
N = matlab.lang.makeValidName(S)
constructs valid MATLAB® identifiers, N
, from input strings, S
. The makeValidName
function does not guarantee the strings in N
are unique.
A valid MATLAB identifier is a character vector of alphanumerics (A–Z, a–z, 0–9) and underscores, such that the first character is a letter and the length of the character vector is less than or equal to namelengthmax.
makeValidName
deletes any whitespace characters before replacing any characters that are not alphanumerics or underscores. If a whitespace character is followed by a lowercase letter, makeValidName
converts the letter to the corresponding uppercase character.
So for example:
>> matlab.lang.makeValidName(["_privateField", "some name"])
yields:
ans =
1×2 string array
"x_privateField" "someName"
I am not sure it applies to your use case, but you might want to look at: Why Variables Should Not Be Named Dynamically (eval
).
Perhaps what you really want to do is check whether variables with certain names exist, then do something accordingly - in which case you could use the exist
function:
tf = exist('varName','var')
So for example:
if exist('a','var') && exist('b','var')
res = someFunction(a,b);
else
res = someFunction(default_a,default_b);
end