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

How can i save previous value of variable in Matlab Function

您好,我想知道如何在 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

感谢您的帮助

制作yppersistent

function y = fcn(x,d,varargin)
persistent yp 

if nargin>2 
   yp = varargin{1};
end
...
yp=y;
end

由于 yp 现在是永久性的,下次您调用函数 yp 时将已经保存您之前计算的 y 的值。唯一的问题是不要像目前那样用 yp=0 覆盖它。

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

除了 persistent 变量之外,您还可以将值保存在嵌套函数和 return 该函数的句柄中:

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 Function 块中使用 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