MATLAB: Assigning imported data to variable names (also imported)

eval

Hello everyone,
I have a problem to assign names to data from imported excel file.
The data is exported from the file:
filename='Input parameters.xlsx';
sheet='Sheet1';
xlRange='A1:B21';
[VarVal VarNam]=xlsread('Input parameters.xlsx',sheet,xlRange)
The assignment I use is as follows:
vals=VarVal'
vars = VarNam'
for i = vals
eval([vars{i} '= vals(i)'])
end
Anyone knows how to fix it? Basically the purpose is that I would like to insert parameters into excel and then run my model in matlab without interfering in command window.

Best Answer

If you want to write efficient code that is easy to debug, read my answer below. If you wish to use eval to assign values to variables (for some reason beginners often want to do this), then read these first:
A much better solution is to convert the data into a structure:
>> VarVal = [1,2,3];
>> VarNam = {'A','B','C'};
>> V = vertcat(VarNam,num2cell(VarVal));
>> S = struct(V{:});
>> S.A
ans = 1
>> S.C
ans = 3
If you have a newer MATLAB version, a table might be suitable too:
See, MATLAB is simple once you stop using awful eval.
Related Question