Need appropriate for loop with if condition
Show older comments
I need to calculate V with some T value conditions, if T satisfies first condition I got to get desired values but if T lies in second or third condition, I am not able to represent the command appropriately. I will be grateful if I could get some correction. What I am trying to do is, say for second condition [elseif (423.85<T(j))&&(T(j)<=647.1)] for i=1, I made T values constant at 423.85, but for i=2 and i=3(here I means it should take up 2nd and 3rd valuesof Vc, Zc, Tc in loop as normal) I have written statements to be solved with given T(j). Similarly if third condition is true T is made constant, for i=1 T=423.85, for i=2, T=647.1 and for i=3 it should solve for given T(j)
function [V] = SolventMV(T,xm)
xm=[ 0.000006250 0.000006199 0.000004616;
0.4313 0.4315 0.4315;
0.2714 0.2681 0.2653];
T=[394.15; 399.15; 500.15 ];
Vc= [121.90 55.9 155];
Zc= [0.287 0.229 0.265];
Tc= [423.85 647.1 819.15];
N=length(T);
V=zeros(N,1);
vm=zeros(N,3);
v=zeros(N,3);
Tr=zeros(N,3);
for j=1:N
if (T(j)<=423.85)
for i=1:3
Tr(j,i)=T(j)/Tc(i);
vm(j,i)=Vc(i)*(Zc(i)^((1-Tr(j,i))^0.286));
v(j,i)=xm(i,j)*vm(j,i);
V(j)=sum(v(j,:))/sum(xm(:,j));
end
elseif (423.85<T(j))&&(T(j)<=647.1)
for i=1
Tr(i)=423.85/Tc(i);
vm(j,i)=Vc(i)*(Zc(i)^((1-Tr(i))^0.286));
v(j,i)=xm(i,j)*vm(j,i);
for i=2:3
Tr(i)=T(j)/Tc(i);
vm(j,i)=Vc(i)*(Zc(i)^((1-Tr(i))^0.286));
v(j,i)=xm(i,j)*vm(j,i);
end
V(j)=sum(v(j,:))/sum(xm(:,j));
end
elseif (647.1<T(j))&&(T(j)<=819.15)
for i=1
Tr(i)=423.85/Tc(i);
vm(j,i)=Vc(i)*(Zc(i)^((1-Tr(i))^0.286));
v(j,i)=xm(i,j)*vm(j,i);
for i=2
Tr(i)=647.1/Tc(i);
vm(j,i)=Vc(i)*(Zc(i)^((1-Tr(i))^0.286));
v(j,i)=xm(i,j)*vm(j,i);
for i=3
Tr(i)=T/Tc(i);
vm(j,i)=Vc(i)*(Zc(i)^((1-Tr(i))^0.286));
v(j,i)=xm(i,j)*vm(j,i);
end
end
V(j)=sum(v(j,:))/sum(xm(:,j));
end
end
Tr
vm
v
V
end
end
8 Comments
per isakson
on 29 Dec 2020
You use the same index in nested for-loops
for i = 1
for i = 2
for i = 3
end
end
end
Is that by purpose? It might work, but it's definitely not recommended.
GAGANDEEP KAUR
on 29 Dec 2020
%if true
for i = 1:3
if i == 1
% your code
elseif i == 2
% your code
elseif i == 3
% Your code
end
end
You can use this for loop structure inside the if else since you have different code lines for each iteration of variable i
VBBV
on 29 Dec 2020
This way you get rid of multiple for loops
GAGANDEEP KAUR
on 29 Dec 2020
VBBV
on 29 Dec 2020
What error do you get?
GAGANDEEP KAUR
on 30 Dec 2020
VBBV
on 30 Dec 2020
Note that the operator '==' is logical equivalent to equal for checking sameness. It can't be used in for loop iterative index as you have done in the program.
Look into the program structure in my earlier comment. It should work fine without errors.
Answers (0)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!