time dependent constant to solve 1st order ODE via ode45
2 views (last 30 days)
Show older comments
I am able to solve my diff eq with ode45, however, I need one of my constants to change value once the output reaches a certain value. For context, this is to solve for the temperature in a simple energy balance for a stirred tank.
I need Tw to change to 15C once T reaches 34.7C
Code is as follows:
function diffeqs= ode_sys(t,var)
T=var(1);
dH=1200;
M=2300;
cp=4.2;
F=0.125;
Tw=20;
Tin=25;
U=3.4;
A=2.8;
diffeqs(1,1)=((F*cp*(Tin-T))+(F*cp*(Tin-T))+(F*dH)-(U*A*(T-Tw)))/(M*cp)
end
***NEW SCRIPT***
tspan=[0:9000];
IC=(25); %initial Temp
[t,y]=ode45(@ode_sys,tspan,IC);
figure
plot(t,y,'-')
title('Temperature in CSTR')
xlabel('time/s')
ylabel('Temperature/C')
Accepted Answer
J. Alex Lee
on 29 Jul 2020
Seems like you just need Tw to be a function of T (of var(1)).
function diffeqs= ode_sys(t,var)
T=var(1);
dH=1200;
M=2300;
cp=4.2;
F=0.125;
% Tw=20;
Tin=25;
U=3.4;
A=2.8;
Tw = myfun(T)
diffeqs(1,1)=((F*cp*(Tin-T))+(F*cp*(Tin-T))+(F*dH)-(U*A*(T-Tw)))/(M*cp)
end
function Tw = myfun(T)
% any functional form that you want, including a step function
if T <= 34.7
Tw = 20;
else
Tw = 15;
end
end
I don't know if this "switch" type function is what you really want...should it be a smoother function? You can make the dependence on temperature in any functional form that you want, so just keep that in mind.
Also, I would recomment moving the constants outside of the odefun.
By the way time is not a reliable way to determine temperature..if you know when, then you don't really need to solve the ODE, do you?
2 Comments
J. Alex Lee
on 29 Jul 2020
By the way your system never seems to reach 34.7deg, so the switch will not affect your results.
Below will run, but I don't think the switch-liek function will give you what you want; demonstrated with a switch temperature of 33deg.
clc;
close all;
clear;
tspan=[0:9000];
IC=(25); %initial Temp
TwFunHndl = @TwFunConst;
[t,y]=ode45(@(t,Y)ode_sys(t,Y,TwFunHndl),tspan,IC);
figure; hold on;
plot(t,y,'-')
title('Temperature in CSTR')
xlabel('time/s')
ylabel('Temperature/C')
TwFunHndl = @TwFunSwitch;
[t,y]=ode45(@(t,Y)ode_sys(t,Y,TwFunHndl),tspan,IC);
plot(t,y,'--')
function diffeqs= ode_sys(t,var,TwFunHndl)
T=var(1);
dH=1200;
M=2300;
cp=4.2;
F=0.125;
% Tw=20;
Tin=25;
U=3.4;
A=2.8;
Tw = TwFunHndl(T);
diffeqs(1,1)=((F*cp*(Tin-T))+(F*cp*(Tin-T))+(F*dH)-(U*A*(T-Tw)))/(M*cp);
end
function Tw = TwFunSwitch(T)
% any functional form that you want, including a step function
if T <= 33 % 34.7
Tw = 20;
else
Tw = 15;
end
end
function Tw = TwFunConst(T)
% any functional form that you want, including a step function
Tw = 20;
end
More Answers (0)
See Also
Categories
Find more on Ordinary Differential Equations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!