How do I use persistent variables in MATLAB Function Blocks?
9 ビュー (過去 30 日間)
古いコメントを表示
MathWorks Support Team
2018 年 3 月 9 日
回答済み: MathWorks Support Team
2018 年 4 月 11 日
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.
採用された回答
MathWorks Support Team
2018 年 3 月 9 日
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 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Simulink Functions についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!