Unable to define type of persistent variable inside Simulink Matlab function block

조회 수: 13 (최근 30일)
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
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?

채택된 답변

Tom Bryan
Tom Bryan 2023년 3월 2일
편집: Tom Bryan 님. 2023년 3월 4일
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);
y = u;
a(:) = y;
  댓글 수: 2

댓글을 달려면 로그인하십시오.

추가 답변 (0개)


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




Community Treasure Hunt

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

Start Hunting!

Translated by