Search code examples
matlabsimulink

How can i save previous value of variable in Matlab Function


Hello I would like to know how to save the previous value of an output variable in a matlab function.

function y = fcn(x,d,yp)
yp=0;  %here I want to initialize this value just at the start of simulation
if (x-yp<=d)
    y=x;
else 
    y=yp + d;
end
yp=y;  % here i want to load output value

Thanks for your help


Solution

  • Using a persistent variable is the correct way to go, but as you found out, you cannot use varargin in a MATLAB Function block. The trick is to check whether the variable is empty or not, as in:

    function y = fcn(x,d,yp)
    
    persistent yp
    
    if isempty(yp)
       yp=0;  %only if yp is empty, i.e. at the beginning of the simulation
    end
    
    if (x-yp<=d)
        y=x;
    else 
        y=yp + d;
    end
    
    yp=y;  % here i want to load output value