consolidatemat.m 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. function results = consolidatemat(files,outfile,varsexclude)
  2. % function results = consolidatemat(files,outfile,varsexclude)
  3. %
  4. % <files> is a wildcard matching one or more .mat files
  5. % <outfile> (optional) is a .mat file to write 'results' to.
  6. % if [] or not supplied, don't write to a .mat file.
  7. % <varsexclude> (optional) is a variable name or a cell vector of
  8. % variable names to NOT load. if [] or not supplied, load everything.
  9. %
  10. % we use matchfiles.m to match the <files>.
  11. % we then construct a struct array with elements
  12. % containing the results of loading each .mat file.
  13. % this array is named 'results' and we save it
  14. % to <outfile> if supplied.
  15. %
  16. % example:
  17. % a = 1; b = 2; save('test001.mat','a','b');
  18. % a = 3; b = 4; save('test002.mat','a','b');
  19. % consolidatemat('test*.mat','final.mat');
  20. % results = loadmulti('final.mat','results');
  21. % results(1)
  22. % results(2)
  23. % TODO: what about mismatches in the contents of the files?
  24. % save only the intersection? report to screen?
  25. % input
  26. if ~exist('outfile','var') || isempty(outfile)
  27. outfile = [];
  28. end
  29. if ~exist('varsexclude','var') || isempty(varsexclude)
  30. varsexclude = [];
  31. end
  32. % do it
  33. files = matchfiles(files);
  34. clear results;
  35. fprintf('consolidatemat: ');
  36. for p=1:length(files)
  37. statusdots(p,length(files));
  38. if isempty(varsexclude)
  39. a = load(files{p});
  40. else
  41. a = loadexcept(files{p},varsexclude,1);
  42. end
  43. if exist('results','var')
  44. assert(isequal(sort(fieldnames(results(1))),sort(fieldnames(a))), ...
  45. sprintf('unexpected fields in file "%s"',files{p}));
  46. end
  47. results(p) = a;
  48. end
  49. if ~isempty(outfile)
  50. fprintf('saving...');
  51. save(outfile,'results');
  52. end
  53. fprintf('done.\n');