How do I use persistent variables in MATLAB Function Blocks?
9 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
MathWorks Support Team
am 9 Mär. 2018
Beantwortet: MathWorks Support Team
am 11 Apr. 2018
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.
Akzeptierte Antwort
MathWorks Support Team
am 9 Mär. 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'.
0 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Simulink Functions finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!