MATLAB Answers

how to export multiple .mat files to csv using the automation script?

34 views (last 30 days)
Sandeep GNV
Sandeep GNV on 12 Aug 2021
Commented: Rik on 18 Aug 2021
i have multiple .mat files, each mat file consits of 2 datasets (Input and Output). i was successful to combine Inputs and Outputs in a single .mat file and convert it to .csv file.
>>load('mat_file1.mat');
%2 files are loaded in workspace (Input.mat 100x10 and Output.mat 100x10)
>>I/O_file1 = [Input Outpt];
%single MAT file created (I/O_file1.mat 100x20)
>>xlswrite('I/O_file1.csv', mat_file1.mat);
%CSV file created
But there are several MAT files in a single folder such as ( mat_file1.mat, mat_file2.mat, mat_file3.mat, mat_file4.mat, mat_file5.mat .....)
Now i need an Automation script so that i can convert all the MAT files present in the folder at once.

Accepted Answer

Rik
Rik on 12 Aug 2021
Edited: Rik on 12 Aug 2021
Load to a struct:
base=sprintf('mat_file%d',1);
S=load([base '.mat']);
data=[S.([base '_Inputs']) S.([base '_Outputs'])];
xlswrite([base '.csv'],data);
  1 Comment
Sandeep GNV
Sandeep GNV on 17 Aug 2021
thanks for the above solution, it worked. but i have a another problem following to that, i need to add a Row with the Column Names before converting it to the .csv file.

Sign in to comment.

More Answers (1)

Sandeep GNV
Sandeep GNV on 18 Aug 2021
i have set of MAT files ina folder so i wrote an automation code to convert the set of MAT files in folder to CSV files all at a time. each MAT file consits of 2 datasets (Inputs and Outputs).
for i = 1:4; for j = 0:50:100
base=sprintf('Heating_Data1_0C_RB%d_Comb%d',j,i);
S=load([base '.mat']);
data=[S.([base '_Inputs']) S.([base '_Outputs'])];
xlswrite([base '.csv'],data);
end
end
so this merge the two MAT files(Inputs &Outputs) into a single MAT file and covnerts it to CSV file. but here in the excel sheet you see only the numeric data, so now i need to insert a Row on the top with the column headings.
  1 Comment
Rik
Rik on 18 Aug 2021
You can extend the data variable. You probably need to convert it to a cell array (if it isn't one yet) with num2cell. Then you can trivially add the header.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!