Start Variable/Field with a number
33 views (last 30 days)
Show older comments
Is there any way that a variable or field name can start with a number ? I am coding something to convert a spreadsheet into a ini file , the file is too be read by a computer but one of the fields has to start with a 0 to be read correctly as far as i can see all fields and variables have to start with a letter , I have tried turning 0 into a character and putting it in but that does not work either. HELP!
Answers (3)
Steven Lord
on 6 Aug 2015
No. MATLAB identifiers must satisfy the rules given in the documentation for ISVARNAME, and one of those rules is that the first character MUST be a letter. If it were possible to have an identifier that started with a number, you could write VERY confusing MATLAB code (even more confusing than the code you can write now.)
5 = 6; % If this worked, it would define a variable named 5 whose value was 6.
There are functions you can use to convert identifiers that are not valid variable names into valid variable names. See matlab.lang.makeValidName (or if you're using an older release, GENVARNAME.)
3 Comments
Steven Lord
on 8 Aug 2015
Oh, you could get even more confusing.
assignin('caller', '1', 2)
Walter Roberson
on 8 Aug 2015
It is, by the way, absolutely true that in earlier versions of FORTRAN that if you passed a constant to a subroutine and the subroutine assigned a value to the corresponding parameter, that the value of the constant itself would be changed where-ever else in the routine it happened to be used.
Walter Roberson
on 6 Aug 2015
There is, or at least there used to be, but it is not recommended at all, and requires a call to C code. Many cases can be handled by calling genvarname()
What will the name be used for that it would need to start with a 0 "to be read correctly" ?
5 Comments
Walter Roberson
on 7 Aug 2015
The code that James posted is C code; you would need to put it into a .c file and use mex to compile it to use it.
It is not clear to me why you need to encode those strings as field names. You could instead store the name as data in your struct, and when you wanted to use it, search or index the struct. Eventually you create the .ini file as text
for K = 1 : length(YourStruct)
fprintf(fid, '%s = %s\n', YourStruct(K).name, YourStruct(K).value);
end
John D'Errico
on 6 Aug 2015
Nope. Sorry, but not possible.
Variables and field names must start with a valid character. The character '0' is not one of the allowed characters for this purpose.
0 Comments
See Also
Categories
Find more on String Parsing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!