MATLAB: Convert mat-files into CSV.files

.csv file.mat filecsvdirmutiple

Hey
I want to convert my mat-files to CSV. I have 20 mat-files. They are all in the same folder, so I want to convert everything in this folder to af CSV-file and they end with .mat How can I make a loop that takes the 20 subjects and convert the mat file into CSV? I have tried this but its not working, and of course I have to change the filename every time and its time-consuming:

Best Answer

d=dir(fullpath(dirname,'*.mat'));
for i=1:length(d)
load(d(i).name % will leave whatever variable is in mat-file in memory
[p,n]=fileparts(d(i).name); % get path, name w/o extension
csvwrite([fullfile(p,n) '.csv'],X) % write to name w/ .csv extension
end
The above use X as a placeholder for the variable containing the data LOADed; use whatever is that name. Of course, also assumes all the files are symmetric with the same name; if not use the functional form of load and the appropriate structure name retrieved.
And, of course, this begs the question of why one would do this... .mat files are much more accurate in keeping full precision whereas .csv files are a limited number of decimal places; are much faster to read/write and take up far less disk space besides (albeit that's pretty much a "don't care" item any more).