changing variable names when saving variables
23 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Joel Schelander
am 8 Apr. 2021
Kommentiert: Steven Lord
am 8 Apr. 2021
I am running 36 script from one main script. Every "subscript" saves the variables "GUD" and "I2" like in the part I paste here:
if PR==34
run('H34')
end
if PR==35
run('H35')
end
if PR==36
run('H36')
end
save(sprintf('Allv/Alla/HHAG_%02d',PR), 'GUD');
save(sprintf('Allv/Alla/HHAI_%02d',PR), 'I2');
end
What I want is that, when I open the variables I want it to call them a different name for every subscript. Now the variable is called GUD. in G_01, G_02 and so on.
0 Kommentare
Akzeptierte Antwort
Jan
am 8 Apr. 2021
Bearbeitet: Jan
am 8 Apr. 2021
Hiding an index in the name of a variable is a shot in your knee. See TUTORIAL: Why and how to avoid Eval
A pile of scripts increases the complexity of the code, because scripts can change the variables of the callers. Prefer functions with input and output instead.
Value = cell(1, 3);
iValue = 0;
for k = 34:36
iValue = iValue + 1;
Value{iValue} = feval(sprintf('H%d', k));
end
Now all output values are stored in a cell array and you can access them by an index in a loop.
2 Kommentare
Steven Lord
am 8 Apr. 2021
H1, H2, H3... H36 are scripts calculating the total electricity consumption increase of 1, 2... 36 households.
So when you find a bug in one of those scripts you now need to examine 36 scripts to determine how many need to be modified to fix the bug?
And which of those 36 scripts do you need to run to model a house in the suburbs with a family with 3 kids? How easy is it to decide which of those scripts needs to run?
Don't put data in variable, script, or function names! If I were given this problem I would probably write a function that accepts the different categories and decides what to do based on house type, vehicle, family size, etc. This could also allow you to write smaller functions specific to the category values, use those smaller functions inside the main function, and thus not need to change your "driver" script (which just calls the main function) as the categories change.
function energy = electricityConsumption(houseType, vehicle, familySize, % etc)
Weitere Antworten (1)
Matt J
am 8 Apr. 2021
Bearbeitet: Matt J
am 8 Apr. 2021
What I want is that, when I open the variables I want it to call them a different name for every subscript. Now the variable is called GUD
I really wouldn't recommend that. It's not even recommendable that you use load without an output argument. You should be doing things like this,
G=cell(1,N);
for i=1:N
G{i}=getfield( load(file{i}) ,'GUD');
end
0 Kommentare
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!