How to convert mat files into csvs without changing the names of the files?
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Ameer Hamza
2020-11-12
编辑:Ameer Hamza
2020-11-12
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 个评论
Ameer Hamza
2020-11-12
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
2020-11-12
编辑:Stephen23
2020-11-12
"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?
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Workspace Variables and MAT Files 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!