MATLAB Answers

Vectorization of for loops

1 view (last 30 days)
sko
sko on 25 Feb 2021
Answered: Sindhu Karri on 5 Mar 2021
Hi Guys,
Do you have some idea how to vectorize a piece of my code related to chem eng? I have multiple for loops and although I was thought this is not good in Matlab, I dont seem to get how to vectorize them ... My Cp's and dCpdt's of chemical specie i depends on reactor space coordiante given by l, catalyst particle space coordinate given by k. dCpdt's are time derivates of Cp's definied below in the code and are related to space derivatives (that I discretized using finite difference method). nz, nr are number of reactor/particule discretization respectively, nc is number of chemical species, nreac is number of reactions. You can clearly see that depending on my system I can easily overwhelm Matlab with multiple for loops.
Thank you in advance for your suggestion.
for l=2:ent.nz+1
for i=1:ent.nc
rx.particle(l).Cp(i,ent.nr+1)=rx.Cg(i,l);
for k=1:ent.nr
rx.particle(l).source=0;
f=@kinetics;
reac.rate=f(rx.particle(l).Cp(:,k))
for j=1:ent.nreac
rx.particle(l).source=rx.particle(l).source+reac.nu(i,j)*reac.rate(j);
end
if k==1
rx.particle(l).dCpdt(i,1)=(1/p.epsp)* ...
(3*Deff(i,l)*((rx.particle(l).Cp(i,2)-rx.particle(l).Cp(i,1))/(rx.dr^2))+rx.particle(l).source*p.rhos);
else
r1=(k-1)*rx.dr;
r2=k*rx.dr;
rx.particle(l).dCpdt(i,k)=(1/p.epsp)* ...
((Deff(i,l)/(r1^2))* ...
((r2^2)*(rx.particle(l).Cp(i,k+1)-rx.particle(l).Cp(i,k))/rx.dr ...
-(r1^2)*(rx.particle(l).Cp(i,k)-rx.particle(l).Cp(i,k-1))/rx.dr)/rx.dr+rx.particle(l).source*p.rhos);
end
end
end
end

Categories

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!