How do I use persistent variables in MATLAB Function Blocks?

16 views (last 30 days)
I have a MATLAB function block that uses a persistent variable 'n' to calculate the output.
In my MATLAB function block I initialize persistent variable 'n' as 1 when the input to the MATLAB function block is 0, but I still get an error saying:
Persistent variable 'n' is undefined on some execution paths.
My MATLAB function block takes a counter as input, hence, the input is always 0 at the first time step which leads to initialization of 'n'.
Why am I getting this error and how do I get around it?
Please find a simple model which reproduces this issue.

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 9 Mar 2018
Even though in this model, the input to the MATLAB function block will be 0 at the first time step and hence 'n' will be initialized to 1, Simulink has no way to assert that. In other words, if the input to the MATLAB Function block is changed such that 'u' is not 0 at the first time step, then 'n' will never be initialized. This is the reason behind this error.
In order to resolve this issue, you should initialize your persistent variable using an 'if' statement with a call to 'isempty'.
For example, in the attached model, the correct way to use a persistent variable 'n' would be:
function y = fcn(u)
persistent n
if isempty(n)
n=1;
end
y= n*u;
n=n+1;
Using an 'if' statement with a call to 'isempty' ensures that 'n' is initialized to 1 at the first time step irrespective of the value of 'u'.  

More Answers (0)

Categories

Find more on Interactive Model Editing in Help Center and File Exchange

Products


Release

R2016b

Community Treasure Hunt

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

Start Hunting!