Best way to rename a loaded variable?

148 ビュー (過去 30 日間)
Alec Nagel
Alec Nagel 2012 年 11 月 27 日
コメント済み: Steven Lord 2022 年 3 月 17 日
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
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.
Alec Nagel
Alec Nagel 2012 年 11 月 27 日
True -- I have seen such admonitions too. They might have been what prompted the question, on some subconscious level :) The idea came from the top of my head, and/or someone's code I read. Matt's solution seems so obvious in hindsight, but I don't think I'm alone in not having thought of it and, somewhat guiltily, having resorted to EVAL instead.

サインインしてコメントする。

採用された回答

Matt Fig
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 件のコメント
Maria Ironside
Maria Ironside 2017 年 10 月 3 日
Cool, so easy!
Catriona Fyffe
Catriona Fyffe 2020 年 7 月 14 日
Nice, super helpful!

サインインしてコメントする。

その他の回答 (2 件)

Image Analyst
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.

Stefano Petrò
Stefano Petrò 2022 年 3 月 17 日
A way to do this in a single command is
myNewname = getfield(load(myFile,myVar),myVar);
  1 件のコメント
Steven Lord
Steven Lord 2022 年 3 月 17 日
If you're using release R2019b or later you can use dot indexing into the output of function calls.
myVar = 'cdate';
C = load('census.mat', myVar).(myVar)
C = 21×1
1790 1800 1810 1820 1830 1840 1850 1860 1870 1880

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeWorkspace Variables and MAT Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by