changing variable names when saving variables

51 views (last 30 days)
Joel Schelander
Joel Schelander on 8 Apr 2021
Commented: Steven Lord on 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
if PR==35
if PR==36
save(sprintf('Allv/Alla/HHAG_%02d',PR), 'GUD');
save(sprintf('Allv/Alla/HHAI_%02d',PR), 'I2');
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.

Accepted Answer

Jan on 8 Apr 2021
Edited: Jan on 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));
Now all output values are stored in a cell array and you can access them by an index in a loop.
Steven Lord
Steven Lord on 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)

Sign in to comment.

More Answers (1)

Matt J
Matt J on 8 Apr 2021
Edited: Matt J on 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,
for i=1:N
G{i}=getfield( load(file{i}) ,'GUD');




Community Treasure Hunt

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

Start Hunting!