Filling structure with variables from different files

3 ビュー (過去 30 日間)
Zarak Khan
Zarak Khan 2018 年 1 月 5 日
編集済み: Stephen23 2018 年 2 月 5 日
I have a total of 30 mat files , with variables stored in each. Now i would like to access a certain variable from each .mat files and fill them in a single structure.
e.g (case8.mat) and selecting 'Fval2' variable from corresponding mat files
I have come up with this, though its incomplete
S=struct;
S.a=load('case8','Fval2')
S.b=load('case9','Fval2')
This method seems to be time consuming, is there any way to implement a for loop to load files name in order and then assign them in struct accordingly.
Thanks!

回答 (1 件)

Eric
Eric 2018 年 2 月 5 日
You can do:
alpha = 'a':'z';
cases = 8:12;
for i = 1:length(cases)
S.(alpha(i)) = load(['case' num2str(cases(i))],'Fval2');
end
But since you have 30 files, you might want to consider what happens when you hit z... If your files are all similar and have the same variable names you are loading in from each file, you may want consider a structure array:
cases = 8:37
for i = 1:length(cases)
S(i) = load(['case' num2str(cases(i))],'Fval1','Fval2');
end
Which you can then use by doing things like S(2).Fval2. Structure arrays can be a little difficult to work with at times, but might suit your needs perfectly.
  1 件のコメント
Stephen23
Stephen23 2018 年 2 月 5 日
編集済み: Stephen23 2018 年 2 月 5 日
Suggesting a structure array is a good idea. Read more in the documentation:
Note sprintf is more efficient than num2str with concatenation, and it is good practice to avoid length:
for k = 1:numel(cases)
name = sprintf('case%d.mat',k);
S(k) = load(name,'Fval1','Fval2');
end

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

カテゴリ

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

タグ

製品

Community Treasure Hunt

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

Start Hunting!

Translated by