Unable to define type of persistent variable inside Simulink Matlab function block
9 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Charles
el 1 de Mzo. de 2023
Hi,
Attached is a simple system demonstrating what I want to do and so far haven't figured out a way to do.
I would like to run my system using doubles to debug, then convert to fixed-point. The best way I know to do this in a large system is to define a data type, eg: dt_var = fixdt(1, 20, 4);, then refer to it where needed.
I have a Simulink module that's a Matlab function. In it is a persistent variable whose type I'd like to define using the data type I defined:
function y = fcn(u)
% A rather useless function that demonstrates the issue
persistent a
if isempty(a)
a = fi(0, dt_var); % dt_var is undefined
end
y = u;
a = y;
The code inside the if isempty... clause demonstrates what I'd like to do, but cannot, because dt_var is not known inside the function context.
The main problem is for me to be able to access the type dt_var from within the Matlab block. Also, it seems that the compiler doesn't like fixdt within the Matlab function context either:
Function 'fixdt' not supported for code generation.
I should add that I will be using HDL Coder in my actual system, so a solution will have to work in that context.
How do I do this?
Thanks,
Charles
0 comentarios
Respuesta aceptada
Tom Bryan
el 2 de Mzo. de 2023
Editada: Tom Bryan
el 4 de Mzo. de 2023
The issue is that MATLAB Function block doesn't have visibility to dt_var.
MATLAB Function block can’t see variables that are defined outside itself that are not passed in as either inputs or parameters.
MATLAB Function block cannot accept numerictype or fixdt as a parameter, so the fix is to create a prototype fi variable outside the block either in the base workspace using an initialization script, or in a data dictionary. For example, in MATLAB define the following variables.
dt_var = fixdt(1,20,4);
dt_var_prototype = fi(0,dt_var);
Then declare dt_var_prototype as a non-tunable parameter in the MATLAB Function block, and cast 0 to it like the following screenshot. Also note that I added subscripted assignment
a(:) = y;
so that a’s type would not be overwritten by y’s type.
I attached the model and script.
When the type is determined by the type of one of the inputs
If the type of the persistent variable is the same as the input type, then it is not necessary to pass in another variable with type information. So, in this case, the contents of the MATLAB Function block simplifies to the following.
function y = fcn(u)
persistent a
if isempty(a)
a = cast(0,'like',u);
end
y = u;
a(:) = y;
end
2 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Simulink Functions 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!