Filter löschen
Filter löschen

Assigning imported data to variable names (also imported)

8 Ansichten (letzte 30 Tage)
chemeng100
chemeng100 am 29 Mär. 2017
Kommentiert: chemeng100 am 29 Mär. 2017
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.

Akzeptierte Antwort

Stephen23
Stephen23 am 29 Mär. 2017
Bearbeitet: Stephen23 am 29 Mär. 2017
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.
  1 Kommentar
chemeng100
chemeng100 am 29 Mär. 2017
That is what I was searching for.
Thank you very much for quick response.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Variables finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by