# ODE Event Function vs Logical Indexing

2 views (last 30 days)
Christopher McNamara on 4 Oct 2019
Commented: Daniel M on 4 Oct 2019
Hello,
I am writing a very simple code that will approximate the state of charge of a battery. My method is very simple and is shown with the following pseudocode:
% Capacity
Capacity = 500;
% Functions for power flows in and out of the battery
EnergyIn = @(t) "Some function of time for charging power"
EnergyOut = @(t) "Some function of time for discharging power"
% Time derivative of state of charge
SOCDeriv = @(t) EnergyIn(t) - EnergyOut(t);
% Initial state and solver settings
SOC0 = 0.5;
t0 = 0;
tf = 5000;
tSpan = [t0 tf];
Options = odeset('RelTol',1e-6,'AbsTol',1e-6);
% Solve
[t,SOC] = ode45(@(t,y) SOCDeriv(t),tSpan,SOC0,Options);
This worked well but depending on how the EnergyIn or EnergyOut functions behave, can lead to state of charge values of less than 0 or greater than 1 which are not possible. I modified my code to compensate for this by introducing logical indexing to these functions that would turn off input or output power if these limits were exceeded. The change is very simple:
% Capacity
Capacity = 500;
% Functions for power flows in and out of the battery
EnergyIn = @(t,SOC) ("Some function of time for charging power").*(SOC < 1);
EnergyOut = @(t,SOC) ("Some function of time for discharging power").*(SOC > 0)
% Time derivative of state of charge
SOCDeriv = @(t,SOC) EnergyIn(t,SOC) - EnergyOut(t,SOC);
% Initial state and solver settings
SOC0 = 0.5;
t0 = 0;
tf = 5000;
tSpan = [t0 tf];
Options = odeset('RelTol',1e-6,'AbsTol',1e-6);
% Solve
[t,SOC] = ode45(@(t,y) SOCDeriv(t,y),tSpan,SOC0,Options);
This has worked out just as well and seems to have solved my problem without any issue so far. However after browsing around a bit, it seems like I should be using event functions to capture this behavior instead.
Are both of these methods equal in value to solving this problem? Or is this bad practice or an "easy" problem that doesn't require event functions to produce a solution?
Daniel M on 4 Oct 2019
I'm not sure if it's considered bad practice or not, but it isn't an uncommon trick. And if it works, then bully for you! It may even be more maintainable and easier to read than event handling. I suggest reading this website including the comments section for more information.