What is the best way to get the name of a variable in a script?
42 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
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
0 个评论
更多回答(1 个)
Oleksandr Slovak
2018-5-4
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Startup and Shutdown 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!