persistent variable declaration in simulink matlab
7 次查看(过去 30 天)
显示 更早的评论
here is code for the machine learning function
function y = predictActivity(u)%#codegen
persistent n;
if isempty(n)
n = loadLearnerForCoder('EnsembleModel.mat');
end
y = predict(n,u);
end
whenever i use it on command line it works fine but when i make it a block in simulink i get many errors like this
persistent variable 'n' must be assigned before it is used. the only exception is a check using 'isempty(n)' that can be performed prior to assignment.
how to give values to the simulink block of this function
0 个评论
回答(1 个)
Gokhan Atinc
2022-8-24
Hi Arsal,
I was not able reproduce this issue you mentioned, so if you can provide the precise conditions about when you get the error and when you don't (e.g. code when you get the error vs code when you don't, which MATLAB release, are there other error messages, etc.), it would help. I would suggest reaching out to MathWorks Technical Support team with these details for further assistance.
In any case, the way persistent variables are used is precisely the way you've written; the first assignment is wrapped with an isempty call:
persistent mdl;
if isempty(mdl)
mdl = loadLearnerForCoder('EnsembleModel.mat');
end
So the way you've written in your post is the correct way.
Additionally, the machine learning models saved using loadLearnerForCoder can actually work this way:
function y = predictActivity(u)%#codegen
n = loadLearnerForCoder('EnsembleModel.mat');
y = predict(n,u);
end
i.e., without the persistent variable. In the generated code, this is doing the right thing; the model is initialized using loadLearnerForCoder only once in the code. Thus, for simulation with the MATLAB Function Block and code generation, you don't need the persistent variable initialization.
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!