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

时间:2015-05-13 21:59:16

标签: matlab simulink

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

感谢您的帮助

3 个答案:

答案 0 :(得分:4)

制作files() 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替换了函数参数列表中的yp,其中包含可选参数。第一次调用varargin时,您应将其称为fcn,其中零将传递给函数内的y = fcn(x,d,0)。下次你应该在没有第三个参数的情况下调用它,不要覆盖值yp保持(即yp

答案 1 :(得分:3)

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

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);

当我注意到由于没有检查持久变量的初始化而导致性能提高时,我使用它而不是持久变量。

答案 2 :(得分:1)

使用持久变量是正确的方法,但正如您所发现的那样,您不能在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