How to initialize a variable only once in an embedded matlab function?
8 views (last 30 days)
Show older comments
Nikhil on 5 Apr 2013
Commented: MAYANK JHA on 29 Mar 2015
I'm working on a smart metering system simulation.I have a billing algorithm matlab function inserted in my simulation.The inputs are:
1.No of units of energy consumed
3.Price signal from utility
2.zero balance indicator switch
I'm trying to use the following algorithm Store the current units consumed in a variable which will become prev units in the next clock cycle.Then i perform current balance-prev balance in next cycle. Multiply the answer with the current price and add it to a variable y0 which will be subtracted from initial balance to get the current balance.
I want prev_bal=0 and y0=0 in the start.But if i write the 2 statements at the start of the code both variables become 0 at the start of every sampling.As a result the algorithm fails.Please guide me how to set the two variables 0 only for the first sampling or suggest an alternate algorithm.
MAYANK JHA on 29 Mar 2015
did you find a better solution??... try the "persistent" functionality in Matlab function block to initialize. refer here:http://fr.mathworks.com/help/simulink/ug/defining-and-initializing-persistent-variables.html
use isempty command to check and therefore assign the intial value at first instant.
your welcome. :)
Ryan G on 5 Apr 2013
You can try the exist function. This will check to see if they exist. If they do, then you can skip that line of code.
Ryan G on 8 Apr 2013
Will you be generating code for this function? If so, you will need to find another method of doing this.
If not, I think you need to pre-define a before you call exist.
When you call a function extrinsically it uses the mxarray datatype from MATLAB. MATLAB Function Blocks generate code and it can be a bit confusing as to where you need to pre-define variables if you've never done it before.
The line above essentially declares 'a' as a double type so when you call the exist function it will maintain that datatype.
harjot on 29 Oct 2013
Hi Nikhil .. I am facing similar issue . Are you able to initialize the variable inside a function block for just once. I tried the exist function but it seems it dioesn't work inside a function block
Find more on Texas Instruments C2000 Processors 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!