How to store the name of a variable as a string variable?

조회 수: 15 (최근 30일)
Chris
Chris 2024년 4월 25일
답변: Tony 2024년 4월 25일
I want to reuse code that processes data stored in a variable variable (I alter the name of the variable at one location in a script). The output is to be written to an external file accompanied by the name of the input variable. That means I would like to also dynamically access the name of the variable, not only its content.
Note I could use eval to assign the input variable and this certainly would be simple (even if its use is generally frowned upon), but I'd like to implement the alternative of getting the name of the variable as a string and passing this to the output routine.
Is there a way to do this in MATLAB?
Note looks like this has been answered here: https://se.mathworks.com/matlabcentral/answers/382503-how-can-i-get-the-name-of-a-matlab-variable-as-a-string

답변 (1개)

Tony
Tony 2024년 4월 25일
Structures are one way of having dynamic variable names that you can refer using strings. Not sure if you can rename an existing field, but at the worst you could copy the value into a new struct with preferred name.
CurVar = 1;
CurVarName = 'CurVar';
CurStruct = struct(CurVarName, CurVar);
display(CurStruct);
CurStruct = struct with fields:
CurVar: 1
display(fields(CurStruct));
1x1 cell array {'CurVar'}
display(CurStruct.(CurVarName));
1
NewVarName = 'NewVar';
NewStruct = struct(NewVarName, CurStruct.(CurVarName));
display(NewStruct);
NewStruct = struct with fields:
NewVar: 1
display(NewStruct.(NewVarName));
1

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by