Effacer les filtres
Effacer les filtres

Assigning imported data to variable names (also imported)

8 vues (au cours des 30 derniers jours)
chemeng100
chemeng100 le 29 Mar 2017
Commenté : chemeng100 le 29 Mar 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.

Réponse acceptée

Stephen23
Stephen23 le 29 Mar 2017
Modifié(e) : Stephen23 le 29 Mar 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 commentaire
chemeng100
chemeng100 le 29 Mar 2017
That is what I was searching for.
Thank you very much for quick response.

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Variables dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by