How to avoid evalin?

5 ビュー (過去 30 日間)
Adriano Filippo Inno
Adriano Filippo Inno 2019 年 4 月 2 日
コメント済み: Stephen23 2019 年 4 月 2 日
I have a .mat file that contains a large set of vectors. Let's say var1, var2,....varN
I need to use these vectors in a for loop. Here's what I did:
load('GivenFile.mat')
% no other variables saved
Names = who;
N = length(Names);
for i = 1:N
TempVar = evalin('base',Names{i});
...
end
I know that evalin should be avoided so I tried to save the workspace in a structure in order to do:
Tempvar = SavedWorkspace.Names{i}
But I'm not able to save the workspace as a structure.
  4 件のコメント
Rik
Rik 2019 年 4 月 2 日
Feel free to forward this thread to the person who created this mat file. Or this thread.
Adriano Filippo Inno
Adriano Filippo Inno 2019 年 4 月 2 日
My professor did, so is better if I don’t!

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

採用された回答

Rik
Rik 2019 年 4 月 2 日
You can solve it this time by loading into a struct:
S=load('GivenFile.mat');
fn=fieldnames(S);
for n=1:numel(fn)
tempVar=S.(fn{n});
%some useful code:
%...
end
But I second John's suggestion to put it all into a single variable.
As a final remark: always load into a struct, it makes it obvious where variables are coming from, which helps with debugging and future editing.
  2 件のコメント
Adriano Filippo Inno
Adriano Filippo Inno 2019 年 4 月 2 日
Thanks Rik, this exactly solves my problem! I didn’t know that load can save to a structure! Usually I use directly a structure as coding so I never encounter this problem.
Stephen23
Stephen23 2019 年 4 月 2 日
" I didn’t know that load can save to a structure! "
The load documentation explains all of the different load syntaxes:

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeVariables についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by