无法在Matlab中更改持久变量的值

问题描述 投票:0回答:1

我在其中一个simulink功能块中定义了一个函数。在该函数中,我定义了一些持久变量,并希望根据特定条件更改其值。这些持久变量的值没有变化。这是我的代码,

function [er,mem,phi_hat_dot,hdot,ldot,x_hat,x_til1,...
    x_til2,f_hat,g_hat,x_hat_dot,h_bar,ns]= ident(x,u,h,...
    l,phi_hat,gain)
persistent i Z x_tj;            % initialized persistent values
if isempty(i)
    i=0;
end
if isempty(Z)
    Z=zeros(5,15);
end
if isempty(x_tj)
    %si=size(Z);
    x_tj=zeros(length(x),15);
end
Gamma=gain(1);a=gain(2);A=gain(3); % gains
x1=x(1);x2=x(2);                   % state variable
z=[x1,x2,x1*(x1^2+x2^2),x2*(x1^2+x2^2),u]';
hdot=-a*h+z;
ldot=-A*l+x;
ns=1+h'*h+l'*l;
x_bar=x/ns;h_bar=h/ns;l_bar=l/ns;
x_hat=phi_hat*h_bar+a*l_bar;
e=x_hat-x_bar;
%%%%%%%%%Memory Stack%%%%%%%
while i<15               %This is the place where I am altering persistent variables
    Z(:,i+1)=h_bar;
    x_tj(:,i+1)=x_bar;
    i=i+1;
end
mem=x_tj;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%Error Stack%%%%%%%%%%%
%Gamma=102;
si=size(Z);
er=zeros(length(x),si(2));
if i>=15
    for j=1:si(2)
        er(:,j)=x_hat-x_tj(:,j);
    end
    phi_hat_dot=-Gamma*e*h_bar'-Gamma*er*Z';
else
    phi_hat_dot=-Gamma*e*h_bar';
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%Update Law%%%%%%%%%%%
x_til1=x-x_hat;
x_til2=x_bar-x_hat;
f_hat=phi_hat(:,1:4)*z(1:4);
g_hat=phi_hat(:,5)*1;
x_hat_dot=f_hat+g_hat*u;
matlab simulink persistent
1个回答
0
投票

只需查看变量i,并按照您的代码,i只会在模型初始化期间发生变化。

也就是说,在t=0,代码被调用

  • 最初是i = 0;
  • 然后在记忆堆栈中i将从0增加到15

由于你没有在其他任何地方改变i,上面的意思是因为i是持久的,所以其他时候它将具有15的值。

因此,while i < 15循环永远不会执行(在初始化之后),并且您永远不会更改Zx_tj的值(初始化之后)。这也意味着在错误堆栈中,i >= 15代码将始终执行。

如果上述情况没有发生(必须如此)那你看到了什么,你期待什么?

另请注意,您可以稍微简化初始化。在任何时候,当i为空时,Zx_tj将永远是空的,所以没有真正的理由来检查它们。

if isempty(i)
    i=0;
    Z=zeros(5,15);
    %si=size(Z);
    x_tj=zeros(length(x),15);
end
© www.soinside.com 2019 - 2024. All rights reserved.