Saving variables in a live editor script to an excel file
Show older comments
I have a very simple question. I wrote a script in Live Editor (the 2022 version). It uses a FOR loop to update numerical values for certain variables at each iteration. Here's a simplified illustration:
for i=1:10
dog=i^2;
cat=i+5;
rabbit=2*i +3;
end
MY GOAL: At each iteration within the script, I'd like to save the current values of the variables to an excel sheet, such that the heading of the first column is "dog", the second column "cat, and the third "rabbit", and under each heading is the data for that variable. Here's a sample of what the excel sheet should look like:
dog cat rabbit
1 6 5
4 7 7
9 8 9
etc., etc., etc.
Note that the three variables, dog, cat, and rabbit get OVERWRITTEN at each iteration -- i.e., the variables are scalars, not arrays, and for various reasons I'd like to keep them as they are. Instead, I just want to insert a line into the FOR loop, maybe using something like xlswrite??? in order to append the current values to the excel file. I tried reading the answers to similar questions in this forum, but couldn't follow them very well. So a very simplified answer would be very much appreciated. Thank you.
Answers (1)
Using writecell would probably be the easiest way to do this. You can use 'WriteMode','append' where appropriate.
% specify the file to write to:
output_file = 'output.xlsx';
% write the header line, overwriting the file if it already exists:
writecell({'dog' 'cat' 'rabbit'},output_file);
for i=1:10
dog=i^2;
cat=i+5;
rabbit=2*i +3;
% write a new row of data, appending to the end:
writecell({dog cat rabbit},output_file,'WriteMode','append');
end
% done. check the file's contents:
C = readcell(output_file)
2 Comments
july verne
on 8 Jun 2022
Voss
on 8 Jun 2022
You're welcome! Any questions, let me know. Otherwise, please "Accept This Answer". Thanks!
Categories
Find more on Data Import from MATLAB 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!