How to convert mat files into csvs without changing the names of the files?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Katie
am 12 Nov. 2020
Bearbeitet: Stephen23
am 12 Nov. 2020
I have a folder containing thousands of .mat files (lets call the folder matfolder), I am trying to convert all of the files into csv files and I want their name to be the exact name they had before converting, what would be the right way of doing it? I tried something like
files = dir('/matfolder/*.mat');
for file = files'
[filepath, name, ext] = fileparts(file);
csvwrite(name + '.csv', readmatrix(file));
end
But this code will not give me any output.
0 Kommentare
Akzeptierte Antwort
Ameer Hamza
am 12 Nov. 2020
Bearbeitet: Ameer Hamza
am 12 Nov. 2020
This assumes that all the .mat files contain a variable names 'X'.
files = dir('/path_to_matfiles/*.mat');
for i = 1:numel(files)
mat_filename = fullfile(files(i).folder, files(i).name);
[~, name] = fileparts(files(i).name);
csv_filename = fullfile(files(i).folder, [name '.csv']);
data = load(mat_filename);
X = data.X;
writematrix(X, csv_filename)
end
6 Kommentare
Ameer Hamza
am 12 Nov. 2020
In addition to the points posted by Stephen, also mention in case of multiple variables, how do you want to export it to a csv file? Do you want to append all the variables together into one matrix (which will only work if their dimensions are compatible).
Stephen23
am 12 Nov. 2020
Bearbeitet: Stephen23
am 12 Nov. 2020
"At the moment, I started off with glootal_flow for example see below ... but I get the error"
We can see that the field glottal_flow contains another structure:
glottal_flow: [1×1 struct]
Apparently the writematrix function will accept numeric matrices, character matrices, categorical matrices, and no doubt a few other types of matrix... but it does not work with structures (I guess mostly because there is no obvious single interpretation of how a structure of any size with any number of fields containing potentially arbitrarily-nested arrays of other classes should be converted into a 2D matrix arrangement like a CSV file or a spreadsheet).
In order to save the data of the glottal_flow structure you will have to investigate it and figure out how its contents can be saved. The contents could be any number of other arrays or any size or class, so there is no simple solution for saving its contents, you have to look inside and decide what would work.
"I am not sure if it is possible to have all of the variables in one csv, but if it is possible, it would be great."
Consider the 'myfile.mat' file from my previous comment: how would you arrange that in a 2D CSV file?
May I ask why this conversion is required? What processing will you perform on them?
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Workspace Variables and MAT Files finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!