How to convert a large set of variables in the MATLAB workspace into an Excel file?

4 views (last 30 days)
I want to take my Workspace variables and download them as an Excel file. Here's how I am doing it
% Clean your workspace
clear
close
clc
% Create variables
a = "Hello World";
b = "Today is Friday";
c = "I am happy";
% Define to filenames
varsFile = "workspace.csv";
% Convert variables to tables
dataTable = table(a, b, c);
% Write the tables to their respective files
writetable(dataTable, varsFile);
But suppose that have many many variables. How can I do this without calling each single variable. Is there a loop that can do this for me given a large set of variables? Thanks!
  3 Comments
Stephen23
Stephen23 on 21 Sep 2021
Storing all of your hundreds of arrays in one structure would make your task easy and efficient.
Unfortunately you have lots of separate variables, which makes this task complex and inefficient.

Sign in to comment.

Answers (1)

Image Analyst
Image Analyst on 21 Sep 2021
Try this and adapt as needed:
% Create variables
a = "Hello World";
b = "Today is Friday";
c = "I am happy";
% Define workbook filename.
varsFile = "workspace.csv";
s = whos;
variableNames = {s.name}
for k = 1 : length(variableNames)
% Write the variable to Excel.
% How you do it depends on what the data type is
% and where you want them to go.
end
  4 Comments
Image Analyst
Image Analyst on 22 Sep 2021
Then just call writecell() inside the loop. I believe each time you call it, it will just blast over the existing workbook, and retain existing values, so make sure you change the sheet or cell location when you do the write so you don't clobber old data with new data.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!