Merge .mat file to one .mat files

5 views (last 30 days)
Yi Xien Yap
Yi Xien Yap on 18 Aug 2022
Edited: Stephen23 on 19 Aug 2022
Hello,
I have 4 .mat files. The content in the .mat contain different variable name (From 1 - 100 for example). What I need to do is to combine the four output in the 4 .mat files to one. The output path of the .mat files is stored in a cell structure. What is the best way to do this??
For example:
  3 Comments
Yi Xien Yap
Yi Xien Yap on 18 Aug 2022
Each mat file contain different cell array. For example in this mat file contain data from 10-20, and another one maybe go from 21 - 30. I want to merge them to one mat to show for instance from 1 - 50
Yi Xien Yap
Yi Xien Yap on 19 Aug 2022
mergestructs = @(a,b,c,d) cell2struct([struct2cell(a);struct2cell(b);struct2cell(c);struct2cell(d)],[fieldnames(a);fieldnames(b);fieldnames(c);fieldnames(d)]);

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 19 Aug 2022
Edited: Stephen23 on 19 Aug 2022
Robust and efficient approach which works for any number of .mat files (unlike the verbose solution you found). Note that any duplicate variable names will be overwritten. Where D is your cell array of the filenames:
F = 'merged.mat';
copyfile(D{1},F)
for k = 2:numel(D)
S = load(D{k});
save(F,'-struct','S','-append')
end
Remember to always LOAD into an output variable:
S = load(..)

More Answers (0)

Products


Release

R2022a

Community Treasure Hunt

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

Start Hunting!