如何将变量的先前值保存在MATLAB函数中



你好,我想知道如何在matlab函数中保存输出变量的先前值。

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

感谢您的帮助

制作yp persistent

function y = fcn(x,d,varargin)
persistent yp 
if nargin>2 
   yp = varargin{1};
end
...
yp=y;
end

由于yp现在是持久的,下次您将调用该函数yp将已经保持您先前计算的y的值。唯一的问题是不像当前那样将其覆盖yp=0

我用varargin替换了函数参数列表中的yp,该函数参数列出了可选参数。您第一次致电fcn时,应将其称为y = fcn(x,d,0),其中零将传递给函数内的yp。下次您应该在没有第三个参数的情况下调用它,而不覆盖yp保持的值(即y = fcn(x,d)

除了持久变量外,您还可以将值保存在嵌套函数中并返回该函数的句柄:

function fun = fcn(yp0)
    yp = yp0;   % declared in the main function scope
    fun = @(x,d) update(x,d); % function handle stores the value a yp above and updates below.
    function y = update(x,d)
        if (x-yp<=d)
            y=x;
        else
            y=yp + d;
        end
        yp = y;     % updated down here
    end
end

然后您将使用它像

fun = fcn(yp0);
y   = fun(x,d);

当我注意到不检查持久变量的初始化时,我会使用它而不是持久变量。

使用持久变量是正确的方法,但是当您发现时,您不能在MATLAB功能块中使用varargin。诀窍是检查变量是否为空,如:

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

最新更新