Turning for loops into functions

6 visualizzazioni (ultimi 30 giorni)
Joel Schelander
Joel Schelander il 11 Apr 2021
Modificato: Jan il 11 Apr 2021
I have 36 different scripts (H1, H2, H3...H36) that calculates the increase in households maximum power demand if Battery electric vehicles(BEV) are introduced.
H2 combines two households and calculates the increase of the two. H2 is below.
I really need to make my scripts go faster, I have heard that using functions is a good way, but I am not sure how to go about it.
Hcombos= %120x2 matrix containing all the possible combinations of households
VID1={};
VID2={};
Vehicle1={};
Vehicle2={};
GUD={};
for i2=1:size(Hcombos,1)
%State combinations
C=Hcombos(i2,1);
C2=Hcombos(i2,2);
INCREASE2={};
HH2=Household(:, C)+Household(:, C2);
for j = 1:nBEV
%If the household has three or more inhabitants then there can be
%two vehicles x=3
if HHPerson(C)>=x
for k=1:nBEV
%There is only one car if
if k==j
Vehicle1{j,k}=BEV(:, j);
VID1{j,k}=ID(j);
else
Vehicle1{j,k}=BEV(:,k)+BEV(:,j);
VID1{j,k}=[ID(j) ID(k)];
end
end
end
if HHPerson(C2)>=x
for k2=1:nBEV
%There is only one car if
if k2==j
Vehicle2{j,k2}=BEV(:, j);
VID2{j,k2}=ID(j);
else
Vehicle2{j,k2}=BEV(:,k2)+BEV(:,j);
VID2{j,k2}=[ID(j) ID(k2)];
end
end
end
if HHPerson(C)<x
for k1=1:nBEV
%There is only one car if
Vehicle1{j, k1} = BEV(:,k1);
VID2{j, k1} = ID(k1);
end
end
if HHPerson(C2)<x
for k22=1:nBEV
%There is only one car if
if k22==j
Vehicle2{j, k22} = BEV(:,k22);
VID2{j, k22} = ID(k22);
end
end
end
end
for jj=1:numel(VID1)
V11=Vehicle1{jj};
ID1=VID1{jj};
for jj2=1:numel(VID2)
V22=Vehicle2{jj2};
ID2=VID2{jj2};
%Removes all doubles
if numel(intersect(ID1,ID2))
continue
end
INCREASE2{jj,jj2}=max(HH2+V11+V22)./max(HH2);
end
end
GUD{i2}=INCREASE2;
end
  1 Commento
Jan
Jan il 11 Apr 2021
Modificato: Jan il 11 Apr 2021
Please post your code in a readable format. Press ctrl-a ctrl-i for a proper indentation and remove the pile of empty lines.
I assume Matlab's editor shows some warnings about the iteratively growing arrays. Take these warnings seriously.

Accedi per commentare.

Risposta accettata

Cris LaPierre
Cris LaPierre il 11 Apr 2021

Più risposte (0)

Categorie

Scopri di più su MATLAB in Help Center e File Exchange

Prodotti


Release

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by