Using for loop within a for loop in MATLAB
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
I need to apply For loop within a loop. As of generally, we apply a for loop(Say j as i used) and for that value another loop( say i here) runs all the statements but here I need to reuse that first loop( j ) again within the statements. If I could get some idea, how to use it repeatedly.
%%Calculate molar volume of solvent mixture
%xm=composition of species in solution
%Vc=critical volume of species
%vm=molar volume of species
%Tr=reduced temperature of species
%T=temperature of solution mixture
%V= molar volume of micture
Vc= [121.90 55.9 155];
Zc= [0.287 0.229 0.265];
Tc= [423.85 647.1 819.15];
xm= [0.1 0.2 0.2];
T=[394.15 399.15 404.15];
V=[0 0 0];
N=length(T);
vm=[0 0 0];
v=[0 0 0];
Tr=[0 0 0];
for j=1:N
if (T(j)<=423.85)
for i=1:1
Tr(i)=T(j)/Tc(i);
vm(i)=Vc(i)*(Zc(i)^((1-Tr(i))^0.286));
v(i)=xm(i)*vm(i);
end
elseif (423.85<T(j))&&(T(j)<=647.1)
for i=1
T= 423.85; %Constant critical temperature of HI
Tr(i)=T/Tc(i);
vm(i)=Vc(i)*(Zc(i)^((1-Tr(i))^0.286));
v(i)=xm(i)*vm(i);
for i=2:3
T=T(j)
Tr(i)=T(j)/Tc(i);
vm(i)=Vc(i)*(Zc(i)^((1-Tr(i))^0.286));
v(i)=xm(i)*vm(i);
end
end
elseif (647.1<T(j))&&(T(j)<=819.15)
for i=1
T=423.85;
Tr(i)=T/Tc(i);
vm(i)=Vc(i)*(Zc(i)^((1-Tr(i))^0.286));
v(i)=xm(i)*vm(i);
for i=2
T=647.1; % critical temperature of H2O
Tr(i)=T/Tc(i);
vm(i)=Vc(i)*(Zc(i)^((1-Tr(i))^0.286));
v(i)=xm(i)*vm(i);
for i=3
T=T(j);
Tr(i)=T(j)/Tc(i);
vm(i)=Vc(i)*(Zc(i)^((1-Tr(i))^0.286));
v(i)=xm(i)*vm(i);
end
end
end
end
Tr
vm
v
V(i)=sum(v(i))/sum(xm(i));
end
disp(V)
2 comentarios
Jan
el 9 de Dic. de 2020
The question is not clear to me yet. What does " reuse that first loop( j ) again within the statements" mean?
What is the purpose of loops over one value? Replace "for i=1" by "i=1;". Nested loops with the same loop counter are confusing only. It is too hard to guess, what you want the code to do.
Respuestas (1)
Jan
el 10 de Dic. de 2020
Cleanup the strange nested loops over scalars:
for i=1
T= 423.85;
Tr(i)=T/Tc(i);
vm(i)=Vc(i)*(Zc(i)^((1-Tr(i))^0.286));
v(i)=xm(i)*vm(i);
for i=2:3
Tr(i)=T/Tc(i);
vm(i)=Vc(i)*(Zc(i)^((1-Tr(i))^0.286));
v(i)=xm(i)*vm(i);
end
end
This is a waste of time only, because you calculate exactly the same in both loops. So simply write:
T = 423.85;
for i = 1:3
Tr(i) = T/Tc(i);
vm(i) = Vc(i)*(Zc(i)^((1-Tr(i))^0.286));
v(i) = xm(i)*vm(i);
end
Or even without a loop:
Tr = T ./ Tc;
vm = Vc .* (Zc .^ ((1 - Tr) .^ 0.286));
v = xm .* vm;
The complete shown code can be simplified to:
Tv = [min(T, 423.85), min(T, 647.1), min(T, 647.1)];
Tr = T ./ Tc;
vm = Vc .* (Zc .^ ((1 - Tr) .^ 0.286));
v = xm .* vm;
V = sum(v) / sum(xm);
disp(V)
No loops, no different branches, no "for i=1".
0 comentarios
Ver también
Categorías
Más información sobre Particle & Nuclear Physics en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!