How to save data from multiple matlab file in a single excel sheet?

12 次查看(过去 30 天)
I have multiple patient files, each with multiple outputs. I managed to export each output in a different excel file, and I created a for loop to go through all the files. The code looks like this (SEF90 is one of the outputs):
for k = 3 : 31
matFileName = sprintf('mat%d.mat', k);
if isfile(matFileName)
matData = load(matFileName);
else
fprintf('File %s does not exist.\n', matFileName);
end
%% SEF90
P = SEF90
V1 = reshape(P,1,20);
writematrix(V1, 'SEF90.xlsx', 'WriteMode','append');
end
The data is saved in the right format in excel and it goes to a new row every time, the problem is that it only writes data from the first file (see screenshot). How can I solve this so that each row is a different file (possibly in order of file number)?
  1 个评论
Antoni Garcia-Herreros
Hello Alice,
You could try to create the 2D array/table with the lines for the different files and then finish the loop and save it as an Excel file
FinalMat=zeros(28,20); % Create the array to store the values of each file
for k = 3 : 31
i=1
matFileName = sprintf('mat%d.mat', k);
if isfile(matFileName)
matData = load(matFileName);
else
fprintf('File %s does not exist.\n', matFileName);
end
%% SEF90
P = SEF90
V1 = reshape(P,1,20);
FinalMat(i,:)=V1;
end
xlswrite('SEF90.xlsx',FinalMat);
Hope this helps!

请先登录,再进行评论。

回答(1 个)

Gyan Vaibhav
Gyan Vaibhav 2023-11-16
Hi Alice,
I understand that your goal is to export the data from various “MAT” files to a single excel file in order of the files.
The code you've shared appears to be mostly correct, however you are trying to append every time in the excel sheet. You need to use the matData for every iteration. Further even when the else condition is valid, the loop is trying to append it to the file, which could lead to wrong output.
This can be done easily by creating an array, by including the data from all the “MAT” files, and then writing this to an excel file.
The above code can be modified as follows:
% Initialize an empty matrix to store all the data
allData = [];
for k = 3 : 31
matFileName = sprintf('mat%d.mat', k);
if isfile(matFileName)
matData = load(matFileName);
%‘SEF90’
P = SEF90;
V1 = reshape(P, 1, 20);
% Append the data to the allData matrix
allData = [allData; V1];
else
fprintf('File %s does not exist.\n', matFileName);
end
end
% Write all the data to the 'SEF90.xlsx' file
writematrix(allData, 'SEF90.xlsx');
Hope this helps and resolves your issue.
Thanks
Gyan

类别

Help CenterFile Exchange 中查找有关 Data Import from MATLAB 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by