MATLAB Answers

I want this code to run only once. Battery Charge/Discharge

50 views (last 30 days)
Alexandre Correia
Alexandre Correia on 15 Apr 2019
Commented: arzu golge on 12 Jun 2020 at 12:55
Hi guys, newbie here on Simulink, this is my first project.
I'm trying to make a battery charge and discharge simulation, I'm using a project i saw in a youtube amateur tutorial, but the example itself is flawed and I'm trying to do my changes. I have this code here:
What it does is when the SOC is > 80% the system is feeding the Load, when it reaches below 40% it turns of the Load and starts charging the batteries.
function [LoadOn, ChargingOn] = fcn(SOC)
LoadOn = 1;
if (SOC>80)
if (SOC<40)
The problem that I'm having is that on the iteration that it reaches >40% it correctly changes the variables to Load=0 and Charge=1, but on the next iteration, due to the second and third line of code, it changes back to LoadOn=1 and Charge=0, when I wanted it only to happen at SOC>80%.
And If I remove the 2nd and 3rd line it gives me an error. Basically what I want to do is that the 2nd and 3rd line only run once.
Any suggestions?

  1 Comment

Nergiz Soyak
Nergiz Soyak on 10 Mar 2020
ıt runs the full code.can you send it back?very urgent needed

Sign in to comment.

Accepted Answer

Ben Cunningham
Ben Cunningham on 15 Apr 2019
Edited: Ben Cunningham on 16 Apr 2019
One way of doing this would be using Persistent variables - but just as with global variables you will need to be careful - to get back to your starting condition you should use 'clear fcn'.
Additionally the persistent variable should not be the output of the function.
function [LoadOn, ChargingOn] = fcn(SOC)
persistent LoadOnPersistent;
persistent ChargingOnPersistent;
if isempty(LoadOnPersistent) % Initial condition
LoadOnPersistent = 1;
ChargingOnPersistent = 0;
if (SOC>80)
if (SOC<40)
LoadOn = LoadOnPersistent;
ChargingOn = ChargingOnPersistent;


Shamsher Ansari
Shamsher Ansari on 31 May 2020
Alexandre Correia can you please share the simulation work for understanding purpose how and where to use this function...... I am learner please help if possible email thank you
arzu golge
arzu golge on 12 Jun 2020 at 12:55
Ben Cunningham can you please share the code with global variables?

Sign in to comment.

More Answers (0)