How do I save the answers from a for loop that solved an equation symbolically?
3 views (last 30 days)
Show older comments
I am trying to save the answers from a for loop in which I solved an equation symbolically.
T_c = 33.145; %crit temp of hydrogen (K)
P_c = 1.3e6; %crit pressure (Pa)
R = 8.314472; %universal gas constant (J/(mol*K)
a = (0.427487*(R^2)*(T_c^2.5))/P_c;
b = (0.08662*R*T_c)/P_c;
x = 0.000051473700293409386773440257598528; %V_m
for P = 2e6:2e6:70e6
syms T_g
eqn = ((8.314472*T_g)/(x-b)) - (a/(sqrt(T_g)*x*(x+b))) == P;
solx = solve(eqn,T_g,"Real",true);
solx = vpa(solx);
end
With this code, I only have the final answer.
I tried using the code below to save the answers from the for loop, but I could not save them and got the answer in the screenshot.
k=0;
for P = 2e6:2e6:70e6
k=k+1;
syms T_g
eqn = ((8.314472*T_g)/(x-b)) - (a/(sqrt(T_g)*x*(x+b))) == P;
solx = solve(eqn,T_g,"Real",true);
solx = vpa(solx);
T_g(:,k) = solx;
end
Can somebody show how to save the answers from a for loop?
0 Comments
Answers (1)
Hassaan
on 9 Aug 2024
T_c = 33.145; % critical temperature of hydrogen (K)
P_c = 1.3e6; % critical pressure (Pa)
R = 8.314472; % universal gas constant (J/(mol*K))
a = (0.427487*(R^2)*(T_c^2.5))/P_c;
b = (0.08662*R*T_c)/P_c;
x = 0.000051473700293409386773440257598528; % V_m
% Preallocate a cell array to store the solutions
T_g_solutions = cell(1, 35);
k = 0;
for P = 2e6:2e6:70e6
k = k + 1;
syms T_g
eqn = ((8.314472*T_g)/(x-b)) - (a/(sqrt(T_g)*x*(x+b))) == P;
solx = solve(eqn, T_g, "Real", true);
solx = vpa(solx);
% Store the solution in the cell array
T_g_solutions{k} = solx;
end
% Now T_g_solutions contains the symbolic solutions for each pressure
T_g_solutions
3 Comments
Torsten
on 11 Aug 2024
Edited: Torsten
on 11 Aug 2024
Since the "solve" command always returns exactly one value for "solx", you can use
T_c = 33.145; % critical temperature of hydrogen (K)
P_c = 1.3e6; % critical pressure (Pa)
R = 8.314472; % universal gas constant (J/(mol*K))
a = (0.427487*(R^2)*(T_c^2.5))/P_c;
b = (0.08662*R*T_c)/P_c;
x = 0.000051473700293409386773440257598528; % V_m
% Preallocate a cell array to store the solutions
T_g_solutions = zeros(1, 35);
k = 0;
for P = 2e6:2e6:70e6
k = k + 1;
syms T_g
eqn = ((8.314472*T_g)/(x-b)) - (a/(sqrt(T_g)*x*(x+b))) == P;
solx = solve(eqn, T_g, "Real", true);
solx = vpa(solx);
% Store the solution in the cell array
T_g_solutions(k) = solx(1);
end
% Now T_g_solutions contains the symbolic solutions for each pressure
plot(2e6:2e6:70e6,T_g_solutions)
grid on
But the code might not give the "correct" value of T if your equation has more than one real solution (I just chose the first one arbitrarily).
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!