MATLAB Answers

How to load variables from Excel into Matlab workspace?

89 views (last 30 days)
Missael Hernandez
Missael Hernandez on 27 Sep 2021 at 5:53
Edited: Missael Hernandez on 1 Oct 2021 at 19:17
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.
  18 Comments
Missael Hernandez
Missael Hernandez on 1 Oct 2021 at 19:16
Yes, the user will not have MATLAB or access to the Simulink link. But I will. I will be in charge of updating the model. This is why I was researching Excel's compatability with MATLAB.
Well I chose Excel because it was the first thing that came to mind. A normal text editor would aslo be fine since that accesible to anyone. Only issue is that I alread wrote the code from Workspace to Excel.

Sign in to comment.

Answers (1)

Matt J
Matt J on 27 Sep 2021 at 6:17
Edited: Matt J on 27 Sep 2021 at 6:17
if you have many columns of data to load, you would not put them in separate workspace variables. You would just read them into a table and hold/manipulate them that way.
dataTable=readtable(varsFile);

Community Treasure Hunt

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

Start Hunting!