Start Variable/Field with a number
조회 수: 16 (최근 30일)
이전 댓글 표시
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!
답변 (3개)
Steven Lord
2015년 8월 6일
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
Steven Lord
2015년 8월 8일
Oh, you could get even more confusing.
assignin('caller', '1', 2)
Walter Roberson
2015년 8월 8일
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
2015년 8월 6일
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
Walter Roberson
2015년 8월 7일
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
2015년 8월 6일
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
참고 항목
카테고리
Help Center 및 File Exchange에서 Workspace Variables and MAT Files에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!