How do I save the answers from a for loop that solved an equation symbolically?
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(1 个)
Hassaan
2024-8-9
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 个评论
Torsten
2024-8-11
编辑:Torsten
2024-8-11
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).
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Calculus 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!