persistent variable declaration in simulink matlab

조회 수: 4 (최근 30일)
arsal javed
arsal javed 2022년 7월 10일
답변: Gokhan Atinc 2022년 8월 24일
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

답변 (1개)

Gokhan Atinc
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.

카테고리

Help CenterFile Exchange에서 Simulink Coder에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by