How do I store the outputs of my ODEs in a structured array?

8 vues (au cours des 30 derniers jours)
Jacob
Jacob le 12 Mar 2023
Commenté : Star Strider le 12 Mar 2023
I can plot it but i need to be able to store the value in an array and im not exaxally sure how you do this. Any help would be much appriciated.
function [dAsdt]=rates(tspan, y)
% Rate constants
K1 = 0.4526;
K2 = 0.3958
K3 = 0.3523
%ODE for each spicies in reactor
dA1dt = -K1*y(1)*y(2) -K2*y(1)*y(4) -K3*y(1)*y(5);
dA2dt = -K1*y(1)*y(2);
dA3dt = K1*y(1)*y(2) +K2*y(1)*y(4) +K3*y(1)*y(5);
dA4dt = K1*y(1)*y(2) -K2*y(1)*y(4);
dA5dt = K2*y(1)*y(4) -K3*y(1)*y(5);
dA6dt = K3*y(1)*y(5);
%combine all ODEs into one matrix
dAsdt = [dA1dt; dA2dt; dA3dt; dA4dt; dA5dt; dA6dt]
%%script file to solve ODEs
%setting the initil conditions
y0 = [3 1 0 0 0 0];
% timespan to solve over
tspan = [0 0.2];
%call function solver and pass our system of reaction equations
[tout,yout]=ode45('rates',tspan,y0);
plot(tout, yout(:,1),'r-',tout,yout(:,2),'b--',tout,yout(:,3),'g:',tout,yout(:,4),'c-',tout,yout(:,5),'m--',tout,yout(:,6),'y:')
legend('[MeOH]','[TG]','[BD]','[DG]','[MG]','[GL]')
xlabel('time (sec)')
ylabel('concentration (Kmol/m^3)')
title('Formation of biodiesel reaction')

Réponse acceptée

Star Strider
Star Strider le 12 Mar 2023
It would be easiest to use a cell array —
[tout,yout]=ode45('rates',tspan,y0);
Results = {t,yout};
This also works in a loop, if for example you wanted to change a parameter between iterations:
for k = 1:N
[tout,yout]=ode45(@(t,y)rates(t,y,p(k),tspan,y0);
Results{k,:} = {t,yout];
end
If you want to save the results to a .mat file, use the save function.
.
  2 commentaires
Jacob
Jacob le 12 Mar 2023
thanks for the help!
Star Strider
Star Strider le 12 Mar 2023
As always, my pleasure!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Environment and Settings dans Help Center et File Exchange

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by