1
votes

In a MATLAB Function block in Simulink, it is possible to implement a persistent variable. However, how would someone proceed to implement the same thing, without the MATLAB function block or other similar scripting approach? In other words, is it possible to replicate the behavior of the persistent variable in Simulink with basic/elementary blocks (without external toolbox)?

function y = fcn(u)
%#codegen
persistent n;
if isempty(n) %%initialize persistent variable
    n = 1;
end
if u == 4 || n == 1
    y = 0;
    n = 2;
elseif n == 2
    if ...
         n = 1;
    else ...
         n = 3;
    end
else
    n = -1;
end
1
Persistent memory like this is equivalent to a Unit Delay. In your example the Initial Condition is 1, the block output is the old n and the logic in your code is used to calculate the (unit delay) block input signal, which is the new n.Phil Goddard

1 Answers

1
votes

You could use a Data Store Memory block to simulate a persistent variable.

Since persistent variables preserve their value across function calls, but can only be accessed within that function, you could set up a Simulink subsystem (represents your function) that contains a Data Store Memory block (represents your persistent variable).