Load variables with same name with uigetfile and give them a new name automatically

3 ビュー (過去 30 日間)
zeu
zeu 2017 年 12 月 4 日
コメント済み: zeu 2017 年 12 月 5 日
I have different variables (cells) in my folder, that have the same name when they are loaded into the workspace with "uigetfile(...)". I would like to give each variable automatically a different name (such as var1, var2, var3...for the consecutive variables), when I load them into the workspace. I started like this but I dont get any further. Can someone help me? Thank you :)
[FileName,PathName] = uigetfile('*.mat','MultiSelect','on');
FileName=FileName';
for i=1:size(FileName,1)
var = load([PathName cell2mat(FileName(i))])
end
somehow I want to give to "var" a different name in every iteration (such as var1 in the first iteraton, var2 in the second and so on...)
  1 件のコメント
Stephen23
Stephen23 2017 年 12 月 4 日
Magically creating or accessing variable names will make your code slow, complex, buggy, and hard to debug. Read this to know why:
Instead of using bad code practices you should simply use indexing, which is simple, neat, and very efficient.

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

採用された回答

KL
KL 2017 年 12 月 4 日
編集済み: KL 2017 年 12 月 4 日
Don't do that!
The better approach to this problem is to use cell array or array of structs. I'd suggest array of structs for this case.
[FileName,PathName] = uigetfile('*.mat','MultiSelect','on');
for k=1:numel(FileName)
var(k).data = load(fullfile(PathName,FileName{k}));
end
  8 件のコメント
KL
KL 2017 年 12 月 4 日
編集済み: KL 2017 年 12 月 4 日
@zeu: Ah ok. Now I understand. I forgot to change the for loop limits when I copy pasted your code. When you say size(FileName,1), it's always returning 1 (since, number of rows will always be one for that variable).
I changed it to numel (number of elemements) and I also added a field called data to the struct array var. Now it should contain data from all files. Please check the edited answer!
zeu
zeu 2017 年 12 月 5 日
Thank you very much :)

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

その他の回答 (0 件)

カテゴリ

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