Save multiple doubles in different sheets of one excel file

6 views (last 30 days)
I have different data, each of them are class doubles and have size (300 x 4). How can I save all of them in different sheets of one excel file? I would also like to name every column in every sheet. I had the following in mind, but open to other codes/ways that work.
example of doubles that i have
my_data: size (300 x 4)
your_data : size (300 x 4)
her_data: size (300 x 4)
% example
col_names = {'MA', 'CA', 'PA', 'TL'} % the first row will name every column with these names in every sheet
data_names = {'my_data', 'your_data', 'her_data'} % each are doubles of dimesnion (300 x 4)
for i = length(data_names)
writetable(..,..,'Combined_Data.xlsx','Sheet',strcat(i))
end
  8 Comments
alphabetagamma
alphabetagamma on 29 Jul 2022
Thanks, but how do I get "YourTable". I only have separate "doubles" to begin with

Sign in to comment.

Answers (1)

Manas
Manas on 3 Oct 2023
Hello,
I understand that you want to save your array data into different sheets of one excel file. One way to do this is using a combination of “writetable()” and “array2table()” MATLAB functions with simple looping techniques.
I have modified your code according to my logic.
% Example data
my_data = rand(300, 4);
your_data = rand(300, 4);
her_data = rand(300, 4);
% Column names for each sheet
col_names = {'MA', 'CA', 'PA', 'TL'};
% Data names and corresponding data matrices
data_names = {'my_data', 'your_data', 'her_data'};
data_matrices = {my_data, your_data, her_data};
% Create a new Excel file
filename = 'Combined_Data.xlsx';
delete(filename);
% Loop through each data set and save it in a separate sheet
for i = 1:length(data_names)
data = data_matrices{i};
sheet_name = data_names{i};
% Convert data to a table and assign column names
data_table = array2table(data, 'VariableNames', col_names);
% Write the table to the Excel file
writetable(data_table, filename, 'Sheet', i);
end
Here, we use the “array2table()” function to convert the matrix into a table and assign a column name to it. Finally we use the “writetable()” function to save the table into the excel sheet.
Hope this helps!

Tags

Community Treasure Hunt

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

Start Hunting!