2015-05-13 32 views

回答

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 
+0

谢谢你队友救了我的命! –

4

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)

+1

谢谢,但我忘了提及,我使用Matlab函数Simulink块,它不能使用此方法。我收到错误消息:顶层函数不能有varargin。 –

+0

@MarcelReisinger作为一个可能的工作,你可以让'yp'' global'而不是'persistent'。然后在你调用'fcn'的循环之前,你可以将它初始化为零(或者任何你喜欢的)'yp = 0',就是这样。但要确保你永远不要再触摸'yp'(在'fcn'之外)。然后在'fcn'中删除'varargin'和'if nargin'块。 – PetrH

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

我用这个,而不是持续性的变量时,我注意到一个业绩增长从没有检查PE的初始化rsistent变量。

+1

谢谢,但我忘了提及,我正在使用Matlab函数Simulink块,它不能使用此方法。我收到错误消息:不支持嵌套功能。 –

相关问题