How can I change this loop so that it has no errors?

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

 Accepted 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.

2 Comments

Hi there,
Thank you so much for helping! Solving this symbolically is my only choice since normal solve doesn't give me the correct answer. I need the values for E1,E2 and Yh2new so that I can do graphs. I am not sure how to do this if everything is converted to cells and expecially when we have 2*1 vectors involved. I am still new so thanks again for helping!
As always, my pleasure!
With respect to the cell arrays, I refer you to: Cell Arrays (link) and Access Data in a Cell Array (link).
Your ‘Z’ equation apparently has two roots after i=96. (Up to then it has a single root.) I am not certain what you are doing, so unfortunately I cannot help you decide which of the roots is the one to use, (or perhaps use the mean of them) since both are positive and real.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!