What is the best way to get the name of a variable in a script?

조회 수: 39 (최근 30일)
Jason Nicholson
Jason Nicholson 2016년 1월 14일
답변: Oleksandr Slovak 2018년 5월 4일
What is the best way to get the name of a variable in a script?
The below code works but I am wondering if there is a built-in function that does this:
getname = @(x) inputname(1);
var = 75;
name = getname(var);
The reason I want the name of a variable is I don't want to hard code the name of a variable into a save command like this:
save('Myfile.mat', 'var');
This seems better:
save('Myfile.mat', getname(var));
When you rename a variable, the hard coded save command breaks.
  댓글 수: 1
Stephen23
Stephen23 2016년 1월 14일
편집: Stephen23 2016년 1월 14일
+1 for a neat solution: save('Myfile.mat',getname(var));

댓글을 달려면 로그인하십시오.

채택된 답변

Guillaume
Guillaume 2016년 1월 14일
No, there is no built-in function and your way is actually clever.
And yes, the fact that load and save require variable names instead of the variable themselves feels awkward and prevent easy refactorisation.
Of course, if you go your way, you have to make sure that the code that reads the mat file can cope with changing variable names

추가 답변 (1개)

Oleksandr Slovak
Oleksandr Slovak 2018년 5월 4일
You can use inputname function for that:
aaa = 16;
safe_any_variable(aaa)
function safe_any_variable(variable_by_value)
variable_name = inputname(1);
mfile_name = [variable_name, '.mat'];
evalin('base', "save('" + mfile_name + "', '" + variable_name + "');");
end

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by