I have multiple for loops and the code is slow. How can I speed it up?

Here is a snippet of the code below. The total code takes around 160s to run and I know For loop are not optimal for Matlab but I am not sure what the alternative is. The purpose of the code is to determine the power necessary to meet the If condition in the first loop and then go to the second loop and determine the system capacity based on the power remaining.
If anyone can help on tips to speed it up that would be great.
for FR = FR
PD1 = 0; PD_Ideal_evapTD = 0;
Td = Tmin;
Qevap = ((FR/3600)*(Hvap)*MC)+(MC*FR*heat/3600);
for j = 0:dx:SA %x = [L/4 L/4 L/4 L/4]
Td = Td + dTdA*dx;
R1 = RT*j/SA;
D_evap = Depthevap(R1,FR,MC);
lambda_peak = 2.8977719./(10.*(Td));
lmin = 0.5*lambda_peak*1e-2; lmax = 2*lambda_peak*1e-2;
PD1 = PD1 + integral(@(l)plank_evap(l,Td,D_evap,T),lmin,lmax)*dx*top_deck*1;
PD_Ideal_evapTD = PD_Ideal_evapTD + integral(@(l)plank_ideal(l,Td,D,T),lmin,lmax)*dx*top_deck;
delta_x = j;
if (PD1/1000) >= Qevap/2
break
end
end
i = i+1;
dx2 = [dx2 ceil(N*delta_x)/N];
dxr = ceil(N*delta_x)/N;
PD2 = 0;PD_Ideal_TD = 0; PD_Ideal2 = 0;
k = 1;
R2 = (1-dxr/SA)*RT;
D = Depth(R2,Tp(k),Y2,FR,MC);
for x = dxr:dx:SA
Td = Td + dTdA*dx;
lambda_peak = 2.8977719./(10.*(Td));
lmin = 0.5*lambda_peak*1e-2; lmax = 2*lambda_peak*1e-2; %m
PD2 = PD2 + integral(@(l)plank(l,Td,D,T),lmin,lmax)*dx*top_deck*1; % W
PD_Ideal_TD = PD_Ideal_TD + integral(@(l)plank_ideal(l,Td,D,T),lmin,lmax)*dx*td; % W
PD_Ideal2 = PD_Ideal2 + integral(@(l)plank_ideal(l,Td,D,T),0.01*lmin,100*lmax)*dx*td; % W
end
k = k+1;
i = i+1;
P_evap_TD = [P_evap_TD PD1/1000];
P_Ideal_evapTD = [P_Ideal_evapTD PD_Ideal_evapTD/1000];
P_TD = [P_TD PD2/1000];%kW
P_Ideal_TD = [P_Ideal_TD PD_Ideal_TD/1000]; %kW
P_Ideal2 = [P_Ideal2 PD_Ideal2/1000];
TransferPower_TD = (P_TD + P_evap_TD)/(P_Ideal_evapTD + P_Ideal_TD);
Factor1 = PD_Ideal_TD/PD_Ideal2;
end
Pavail_TD = P_TD + P_evap_TD;

6 Comments

"I know For loop are not optimal for Matlab"
That is incorrect. If used properly, for loops are quite efficient.
Consider Pre-allocating varibles (such as P_evap_TD) instead of dynamically growing arrays.
It seems you are computing the same integral twice in both the for loops, which could be taxing on the speed of the code. I suggest you compute it once and store it in a variable and use the variable wherever required.
It's difficult to suggest something further without being able to run your code. Can you attach the data you have and the functions used in the above code? Use the paperclip button to attach the files.
Ahh I must have been misinformed about For loops in Matlab then.
I have pre-allocated my variables according to the below snippet. I have noticed though that for P_evap_TD, P_TD etc above, they still give the same error when inside the For loop. If I put it outside the For loop, it only holds the final value, not all the results of the looping.
P_TD = []; P_Ideal_TD = []; P_Ideal2 = [];
dx2 = []; P_evap_TD = [];P_Ideal_evapTD = [];
Tp = 200:10:320;
dTdA = (Tmax-Tmin)/SA;
dx = 0.01;
t1 = 60+273; t2 = 200+273;
heat = -0.0744*(t1-t2) + 0.0054*((t1)^2-(t2)^2)/2;
These are the additional functions and then I have attached data/other functions.
function Ed = plank(lambda,Td,D,T)
h = 6.6261e-34; %m2kg/s Planck's constant
c = 299792458; %ms speed of light
kB = 1.380649e-23; %m2kg/s2/K Stefan-Boltzmann constant
v = 1./lambda; %wavenumber - needed for transmittance
eps1 = 0.7; eps2 = 0.8; %eps1 is biomass, eps2 is steel %eps_effective from above???
Tw = transmittance_extrapolater(T,D,v/100)';
eps_eff = (Tw*eps1*eps2)/(eps2 + eps1 - (Tw*eps1*eps2)); %.*(0.7/0.5); %Ratio to take the change in water across drum
Ed = 2*pi*h*c^2.*eps_eff.*lambda.^-5.*(1./(exp(h*c./(lambda*kB*Td))-1)); %W/m3
end
function Ed = plank_ideal(lambda,Td,~,~)
h = 6.6261e-34; %m2kg/s
c = 299792458; %m/s
kB = 1.380649e-23; %m2kg/s2/K
Tw = 1;
Ed = 2*pi*h*c^2.*Tw.*lambda.^-5.*(1./(exp(h*c./(lambda*kB*Td))-1)); %W/m3
end
function Ed = plank_evap(lambda,Td,D_evap,T) %for water evaporation??
h = 6.6261e-34; %m2kg/s Planck's constant
c = 299792458; %ms speed of light
kB = 1.380649e-23; %m2kg/s2/K Stefan-Boltzmann constant
v = 1./lambda; %wavenumber - needed for transmittance
eps1 = 0.7; eps2 = 0.8;
Tw1 = transmittance_extrapolater_vap(T,D_evap,v/100)';
eps_eff = (Tw1*eps1*eps2)/(eps2 + eps1 - (Tw1*eps1*eps2)); %.*(0.7/0.5); %Ratio to take the change in water across drum
Ed = 2*pi*h*c^2.*eps_eff.*lambda.^-5.*(1./(exp(h*c./(lambda*kB*Td))-1)); %W/m3
end
"I have pre-allocated my variables according to the below snippet."
That is not the kind of preallocation that will help you. Go through the link I shared.
"I have noticed though that for P_evap_TD, P_TD etc above, they still give the same error when inside the For loop."
What error do you get? Please copy and paste the whole error (all of the red text)
Also, I believe you have not attached the function Depth()
D = Depth(R2,Tp(k),Y2,FR,MC);
%Command just above the last for loop
@Matt R It's not that for loops are slow in MATLAB. It's that, in MATLAB, you can often vectorize your loops, which is often faster than for loops. The speed up is from running a line of code once instead of N times.
@Dyuman Joshi Even when I pre-allocate accoridng to the link, the result is the same and the code takes too long. Perhaps I am too impatient but the timer is around 4-5mins.
It's not an error - it's a suggestion from the red line under the variable. "Variable appears to change size on every loop iteration. Consider preallocating for speed."
@Cris LaPierre I have tried vectorization for the outer For loop in the code above (starting "For FR =FR...") and I get the following error:
Error using ()
Query coordinates input arrays must have the same size.
Error in interp2 (line 156)
Vq = F(Xq,Yq);
Error in transmittance_extrapolater_vap (line 6)
p = interp2(D1,v1,T,D_evap,v);
Error in PlanckslawTorrcoal>plank_evap (line 262)
Tw1 = transmittance_extrapolater_vap(T,D_evap,v/100)';
Error in PlanckslawTorrcoal>@(l)plank_evap(l,Td,D_evap,T) (line 92)
PD1 = PD1 + integral(@(l)plank_evap(l,Td,D_evap,T),lmin,lmax).*dx.*top_deck.*1; % W
Error in integralCalc/iterateScalarValued (line 314)
fx = FUN(t);
Error in integralCalc/vadapt (line 132)
[q,errbnd] = iterateScalarValued(u,tinterval,pathlen);
Error in integralCalc (line 75)
[q,errbnd] = vadapt(@AtoBInvTransform,interval);
Error in integral (line 87)
Q = integralCalc(fun,a,b,opstruct);
Error in PlanckslawTorrcoal (line 92)
PD1 = PD1 + integral(@(l)plank_evap(l,Td,D_evap,T),lmin,lmax).*dx.*top_deck.*1; % W
In order to vectorize a for loop, all operations inside the loop must be able to be done as matrix or vector operations. If not, then you may have to use a for loop.

Sign in to comment.

Answers (1)

Hi Matt,
I understand that you want to speed up your execution time of your code.
There are a couple of workarounds to reduce the execution time:
  1. One approach is to vectorize your for loops, which can speed up the execution. You can find more information on how to vectorize loops in this link: Vectorization of loops.
  2. Instead of using regular for loops, you can utilize parallel for-loops. This allows the loops to run in parallel, leading to a decrease in execution time. For more details on parallel for-loops, you can refer to this link: Parallel for-loop.
These techniques can help optimize the execution time of your code and improve its performance.
Hope it helps!

Categories

Find more on MATLAB in Help Center and File Exchange

Products

Release

R2023a

Asked:

on 2 Aug 2023

Answered:

on 23 Aug 2023

Community Treasure Hunt

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

Start Hunting!