# Saving output from function in different categories

1 view (last 30 days)
Joel Schelander on 16 Apr 2021
Answered: Abhishek Gupta on 19 Apr 2021
I have vehicles BEV, the variable can have the value BEVR, BEVU or BEVA.
I have households Household, the variable can have the value House, Apartment and [Apartment House]
The inner loop contains functions for how many households are considered.
My question is how I best can save the variables GUD and GUDID?
for i=1:0
if i==1
BEV=BEVA;
Household=Apartment
end
if i==2
BEV=BEVR;
Household=House;
end
%More if statements...
if i==9
BEV=BEVU
Househol=[Apartment House];
end
for z=1:3
if z==1
[GUD,GUDID]=H1(ID,HHPerson,nBEV,BEV,x,Hcombos,Household,sample);
end
if z==2
[GUD,GUDID]=H2(ID,HHPerson,nBEV,BEV,x,Hcombos,Household,sample);%run('H2')
end
if z==3
[GUD,GUDID]=H3(ID,HHPerson,nBEV,BEV,x,Hcombos,Household,sample);
end
end
end
I have so far tried this, but I need a way to save everything. I guess I can use sprintf within the for loop multiple times, but is there another thats faster?
save(sprintf('BEVU/Apu/AUG%d',z), 'GUD');
save(sprintf('BEVU/Apu/AUI%d',z), 'I2');

Abhishek Gupta on 19 Apr 2021
Hi,
As per my understanding, you want to efficiently save "GUD" and "GUDID" variables in every loop iteration. One way would be to append "GUD" and "GUDID" variables at every iteration. Then, after the for-loop, you can save only these two variables, which contain the value of "GUD" and "GUDID" for every value of z. The sample code is shown below: -
% initialize output variables (let's say A and B)
A = []; B = [];
for z=1:3
%--- get GUD and GUDID ---%
% append the variables into the output variables
A = [A; {GUD}]; B = [B; {GUDID}];
end
% save the output variables
save('A.mat','A'); save('B.mat','B');