89 views (last 30 days)

Show older comments

clear

close

clc

aa="a1";

bb="a2";

cc="a3";

dd="a4";

ee="a5";

ff="a6";

gg="a7";

hh="a8";

ii="a9";

jj="a10";

kk="a11";

ll="a12";

mm="a13";

nn="a14";

oo="a15";

pp="a16";

qq="a17";

rr="a18";

ss="a19";

tt="a20";

uu="a21";

vv="a22";

ww="a23";

xx="a24";

yy="a25";

zz="a26";

save variables % save workspace to variables.mat

data = load('variables'); % load back in and assign to struct variable

f = fieldnames(data); % cell containing variable names

nf = numel(f); % number of variables

sz = zeros(nf,1); % array to hold dimensions of variables

% Here we get variable dimensions for each variable

for j = 1:nf

dataj = data.(f{j}); % load in variable j

% convert char arrays to string

if ischar(dataj)

dataj = convertCharsToStrings(dataj);

data.(f{j}) = dataj;

end

sz(j) = numel(dataj); % size of variable j

end

mxsz = max(sz); % max variable size

c = cell(mxsz+1,nf); % cell array to hold data

c(1,:) = f'; % column headers

for j = 1:nf

dataj = data.(f{j})(:); % variable j (turned into a column vector if necessary)

c(2:sz(j)+1,j) = num2cell(dataj); % assign to cell array

end

T = cell2table(c(2:end,:),'VariableNames',c(1,:));

writetable(T,'variables.xls')

The code above shows how to put my Workspace variables (all strings) into Excel. How can I go backwards? What if I'm given the Excel sheet with the variables, how do I load them into the Workspace. My first attempt was this

% Clean your workspace

clear

close

clc

% Create variables

aa="a1";

bb="a2";

cc="a3";

% Define to filenames

varsFile = "workspace.csv";

% Convert variables to tables

dataTable = table(aa, bb, cc);

% Write the tables to their respective files

writetable(dataTable, varsFile);

But I dont like this method because I have to call each variable and that is tedious if ihave many variables. Thanks.

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

Start Hunting!