您好我想知道如何在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
感谢您的帮助
答案 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