Convert Mat files to csv files

803 views (last 30 days)
Harish M Y
Harish M Y on 6 Feb 2023
Edited: Stephen23 on 6 Feb 2023
Hi Team,
I have a folder which contains multiple mat files which I want to convert it to multiple csv files with the same names and save those in a user specified folder, I am not able to do it as I am new to the software. Could you please help me in solving this.
Thank you

Answers (3)

Sulaymon Eshkabilov
Sulaymon Eshkabilov on 6 Feb 2023
Edited: Sulaymon Eshkabilov on 6 Feb 2023
It can be done in three major steps:
Step 1. Load data from *.mat file
FN = input('Enter *.mat file name: ', 's');
D = load([FN, '.mat']);
Step 2. Convert data to a necessary data type if required. If the data is only a matrix ( or numerical array). This step can be avoided
D = table(D);
Step 3. Data export into *.csv:
writetable(D, ([FN '.csv']))

Vinayak Choyyan
Vinayak Choyyan on 6 Feb 2023
Hi Harish,
As per my understanding, you have a folder with many mat files. I assume each mat file has data store in a similar format. You would like to convert these mat files to csv files with the same name as the mat file, and then store each csv file in a user defined location. I assume you want to define a different location for each csv file.
Please try the following draft code to solve the issue you are facing.
x=dir('*.mat');
%load all file's details with .mat extension from current directory and
%store it to variable x
for i=1:length(x)
filename=x(i).name;
s=load(filename);
%variable s has all data for the current mat file selected in the current
%loop iteration
%depending on how data is stored in each mat file, load a variable, say
%T, as table, with data from the mat file. You can see this in the
%example linked below
%take input from user as to which path to store the current csv file.
%there are many ways of getting user input. one of them is shown below
prompt = "Enter the location to store "+filename(1:end-4)+".csv :";
path = input(prompt,"s");
%if you wish to have the same user defined location for all the csv
%files, move the above line to outside the for loop.
%write the data, in table T, to a csv file with the same name as mat file
%and save it to the location specified by the user.
writetable(T, path + filename(1:end-4) + ".csv", 'Delimiter', ',');
end
Please input the user defined location ending with / as it will be concatenated with the file name while storing the csv file.
Please refer the following documentation to see examples on how to write data to a csv file: https://in.mathworks.com/help/matlab/ref/writetable.html#buezy56-5
You can also refer to Request user input - MATLAB input - MathWorks India to read more on how to take input from user at command line and List folder contents - MATLAB dir - MathWorks India to read more on how to get data on files in a directory.

Sarvesh Kale
Sarvesh Kale on 6 Feb 2023
Edited: Sarvesh Kale on 6 Feb 2023
As per my understanding you are trying to write the mat files into excel files with name same as that of mat files, following code achieves the your goal, the following script works when only mat files are present in a given folder and make sure your present working directory is also set to the folder containing the mat files, also load the mat files into workspace , You can import all the mat files into workspace using the import option in the Home tab labeled as 'Import Data'.
path=dir('C:\Users\experiment\matfiles'); % path to folder having all the mat files
array = {path.name} ; % this will have your mat files names as cell array
n = length(array) ; % gives number of mat files + 2 (present and parent directory name count included)
for i = 3:n
x=array{i} ; % character vector
x=x(1:end-4); % extracts the name
csvwrite(num2str(x)+".csv",eval(x)); % write a1.mat to a1.csv provided a1.mat is loaded into workspace
end
This script will save the csv files in the same folder, however you can modify the first argument to csvwrite for examples if you want them to be on your Documents then the first argument will be "C:\Users\Public\Documents\"+num2str(x)+".csv" i.e the path to folder followed by the file name you want for the csv file. Hope this answers your query
  1 Comment
Stephen23
Stephen23 on 6 Feb 2023
Edited: Stephen23 on 6 Feb 2023
Do NOT follow this fragile, buggy, very badly-written code!
The line
path=dir(..)
shadows the important inbuilt function PATH(), rendering it useless. The name is misleading in any case. The line
for i = 3:n
is a fragile, buggy atttempt at ignoring the dot-directory names. Any code that assumes that the dot-directory names are the first two returned by DIR is buggy. This topic has been discussed many times on this forum:
As Walter Roberson wrote in that last link: "In short: if your code assumes that '.' and '..' are the first two entries in a directory, your code has a bug (even in MS Windows). If your code assumes that directory entries are returned in any sorted order, your code has a bug (in all OS.)"
Fragile attempt to remove the file extension from the filename:
x(1:end-4)
Robust and reliable approach:
The line
csvwrite(num2str(x)+".csv",eval(x));
is very badly-written, buggy code. In general it will simply throw an error (but more specifically its behavior will depend on what variables you happen to have in the MATLAB workspace).
Lets try it right now. First lets create some MAT files:
mkdir ./mytest
A = 1.2; save ./mytest/test1.mat A
A = 3.4; save ./mytest/test2.mat A
A = 5.6; save ./mytest/test3.mat A
clearvars
Now lets run the author's code:
P = dir('./mytest'); % path to folder having all the mat files
array = {P.name} % this will have your mat files names as cell array
array = 1×5 cell array
{'.'} {'..'} {'test1.mat'} {'test2.mat'} {'test3.mat'}
n = length(array); % gives number of mat files + 2 (present and parent directory name count included)
for i = 3:n
x=array{i} ; % character vector
x=x(1:end-4); % extracts the name
csvwrite(num2str(x)+".csv",eval(x)); % write a1.mat to a1.csv provided a1.mat is loaded into workspace
end
Error using eval
Unrecognized function or variable 'test1'.
Nope, it does not work. Using magical EVAL() does not help (it rarely does), just obfuscates and causes bugs. Testing code is also recommended. Also note at the very top of the CSVWRITE() documentation:
IGNORE this very badly-written, buggy code.

Sign in to comment.

Categories

Find more on File Operations 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!