converting a.mat of different folder to one csv file.

4 views (last 30 days)
I want to convert my mat-files to CSV. I have 20 mat-files. They are all in the same directory but in different 20 folder kept in paralle , so I want to convert all the .mat file of every folder to one CSV-file and they end with .mat How can I make a loop that takes the 20 .mat file from different folder and convert the mat file into CSV? I have tried this but it is not working , Any help or suggestion is welcomed.

Answers (1)

Walter Roberson
Walter Roberson on 19 Oct 2017
Edited: Walter Roberson on 19 Oct 2017
projectdir = 'c:\parent\directory\of\all\folders';
foldinfo = dir(projectdir);
foldinfo(~[foldinfo.isdir]) = []; %eliminate non-folders
foldinfo(ismember({foldinfo.name}, {'.', '..'}) = []; %eliminate . and ..
foldnames = fullfile(projectdir, {foldinfo.name});
overall_content = [];
looking_for_first = true;
for foldidx = 1 : length(foldnames)
thisfolder = foldnames{foldidx};
dinfo = dir( fullfile(thisfolder, '*.mat') );
matfilenames = fullfile(thisfolder, {dinfo.name});
for fileidx = 1 : length(matfilenames)
thisfile = matfilenames{fileidx};
try
this_content = load(thisfile);
varnames = fieldnames(this_content);
if ~isempty(varnames)
firstvar = varnames{1};
content = this_content.(firstvar);
if looking_for_first
overall_content = content;
looking_for_first = false;
else
overall_content = [overall_content; content];
end
end
catch
end
end %fileidx
end %foldidx
if isempty(overall_content)
fprintf('No usableable .mat files found\n');
else
csvwrite('OutputFile.csv', overall_content);
end
This code assumes that it is the first variable in each file that is to be written, and that the way the content is to be written is to place it all in rows one after the other.

Categories

Find more on Printing and Saving in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!