Best way to rename a loaded variable?
289 次查看(过去 30 天)
显示 更早的评论
Say that I have a .mat file that contains a variable, and I need to load this variable and give it a different name. Is there any other (/better) way to do this than:
load(myFile, myVar)
eval(['myNewname = ' myVar '; clear ' myVar])
?
2 个评论
Jan
2012-11-27
Where does this EVAL idea come from? Did you find EVAL in the documentation or did you see it in an example?
I ask, because it is such frequently suggested to avoid EVAL in this and other Matlab forums for so many years, that I actually expect, that this method should be extinct already.
采纳的回答
Matt Fig
2012-11-27
编辑:Matt Fig
2012-11-27
Say you have the name of your variable:
VAR = 'S';
Now you want to load that variable, but with the name T. This method follows the general rule of thumb to avoid 'poofing' variables into the workspace.
T = load('myfile',VAR); % Function output form of LOAD
T = T.(VAR)
3 个评论
更多回答(2 个)
Image Analyst
2015-2-18
I'd do it this way:
storedStructure = load(myFile, 'myVar'); % Load in ONLY the myVar variable.
myNewname = storedStructure.myVar; % Assign it to a new variable with different name.
clear('storedStructure'); % If it's really not needed any longer.
Same net effect, it just uses the names Alec gave, and avoids dynamic structure fields, which are a bit advanced for beginners and not necessary here if you know the actual name.
0 个评论
Stefano Petrò
2022-3-17
A way to do this in a single command is
myNewname = getfield(load(myFile,myVar),myVar);
1 个评论
Steven Lord
2022-3-17
myVar = 'cdate';
C = load('census.mat', myVar).(myVar)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!