persistent variable declaration in simulink matlab

3 visualizaciones (últimos 30 días)
arsal javed
arsal javed el 10 de Jul. de 2022
Respondida: Gokhan Atinc el 24 de Ag. de 2022
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

Respuestas (1)

Gokhan Atinc
Gokhan Atinc el 24 de Ag. de 2022
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.

Categorías

Más información sobre Simulink Coder en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by