首页 > 解决方案 > Unable to change the value of a persistent variable in Matlab

问题描述

I have a function defined in one of the simulink function blocks. In that function I have defined some persistent variables and wish to change their values based on certain condition. The values of those persistent variable isnt changing. Here is my code,

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;

标签: matlabsimulinkpersistent

解决方案


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

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

  • 最初i = 0;
  • 然后在内存堆栈 i中将从0增加到15

由于您不会i在其他任何地方进行更改,因此上述意味着因为i是持久的,所以在所有其他时间它将具有15.

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

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

另请注意,您可以稍微简化初始化。任何时候什么时候i都是空的,Z而且x_tj永远都是空的,所以没有真正的理由去检查它们。

if isempty(i)
    i=0;
    Z=zeros(5,15);
    %si=size(Z);
    x_tj=zeros(length(x),15);
end

推荐阅读