MATLAB: How to change this loop so that it has no errors

loopsymbolic

syms e1 e2
digits(4)
for i=1:99
x(i)=0.1*(99-i);
j(i)=0.1*i;
Yco=(e1-e2)/(10+2*e1);
Yh2=(3*e1+e2)/(10+2*e1);
Yh2o(i)=(x(i)-e1-e2)/(10-2*e1);
Yco2=e2/(10+2*e1);
Ych4(i)=(j(i)-e1)/(10+2*e1);
K1(i)=(Yco*((Yh2)^3))/(Ych4(i)*Yh2o(i))==1.93*10^-4;
K2(i)=(Yco2*Yh2)/(Yco*Yh2o(i))==5.528;
Z(i)=vpasolve([K1(i),K2(i)],[e1,e2],[0 1; 0 1],'Random',true);
E1(i)=Z(i).e1;
E2(i)=Z(i).e2;
Yh2new(i)=(3.*E1(i)+E2(i)./(10+2.*E1(i)));
end

Best Answer

  • At i=97, ‘e1’ and ‘e2’ become (2x1) vectors rather than scalars as they are for the first 96 iterations. The easiest way to deal with that problem is to make ‘E1’, ‘E2’ and ‘Yh2new’ cell arrays. You can sort those out later:
    E1{i}=Z(i).e1;
    E2{i}=Z(i).e2;
    Yh2new{i}=(3.*E1{i}+E2{i}./(10+2.*E1{i}));
    With those changes, your loop runs without error.
    I am confident that you could avoid all those problems and the considerable time it takes for your loop by using numeric functions rather than symbolic variables and functions, although you might still need to use cell arrays to store the vectors. Since I have no idea what you are doing, I will leave that to you.