matlab - 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;
解决方案
仅查看变量i
并遵循您的代码,i
只会在模型初始化期间发生变化。
也就是说,在 处t=0
,代码被调用并且
- 最初
i = 0;
- 然后在内存堆栈
i
中将从0
增加到15
由于您不会i
在其他任何地方进行更改,因此上述意味着因为i
是持久的,所以在所有其他时间它将具有15
.
因此,while i < 15
循环永远不会执行(在初始化之后),并且您永远不会更改Z
and的值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
推荐阅读
- excel - Excel 中的唯一排名
- python - 如何获取 matplotlib 中所有标记的列表?
- python - 使用机械汤输入后显示为输入选项 - Python
- azure-active-directory - 将所有者添加到 Graph 中的组时未收到电子邮件
- django - 修复错误:django.db.utils.OperationalError: no such table: auth_group
- docker - 无法在 Mac OS 主机上的两个 Docker 容器之间发送/接收 UDP 通信
- c# - 为什么 C# 表单应用程序中的 Firebase 不是实时的?
- java - 实现与firebase一起使用的倒数计时器
- batch-file - 批处理文件到当前目录的相对路径
- android - Android Studio(未安装),当在机器上安装 Android Studio 时运行颤振医生