如何在 ode45 中使用全局变量?

How to use global variable with ode45?

我想在我的 ode45 函数中使用一个在另一个函数中计算的变量值。为此,我使用 global 在所有函数中访问该变量,但它不能以这种方式工作。我的主要功能代码如下:

function window_sine
%%%%%%% Here is the global variable
global vgth;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

epsilon0=8.85*10^-12;
d_mos=0.65*10^-9;
epsilon_mos=5*epsilon0;
d_g=20*10^-9;
epsilon_g=10*epsilon0;
vt=0;
e=1.6*10^-19;  
n=[];
i=1;
t2=[];
u=30; % cm^2/v*S
h=1.05*10^-34;  % j*s
cond_d=e^2/h;
ex=1.5;
%Capacitor Calaculation
c_g=(epsilon_g/d_g);
c_mos=(epsilon_mos/d_mos);
c_t=1/((1/c_g)+(1/c_mos));
step=0.1;
t = 0:step:10;
%Input Voltage 
vg =t;
 % Surface Voltage

vs=(1-(c_t/c_g))*vg;

vg2=vg(1:(length(vg)-1));

%Condition
while i<length(vg)
n(i)=((c_g*(vg(i)-vs(i)-vt))/e)*(10^-4);% this 10^-4 is for cm^2 unit 
if n(i) >= 6.70*10^12 & n(i) <= 6.82*10^12
%%%%%%% Here is the simple calculation of vgth %%%%%%%%%%%%%%
vgth=vg(i);
disp(vgth);
end
i=i+1;
end
figure
plot(vg2,n)
title('Carrier Concentration vs Gate input')
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%ode function calling............
p0=0.01;

[t,p] = ode45(@state,t,p0);

%plotting state variable..................
figure
plot(t,p)
title('Percolation vs input voltage')
p2=p(1:(length(p)-1));
figure
plot(n,p2)
title('Percolation vs carrier concentration')
%%%%%%%%%%%%%%%%%%%%%% Here is the ode45 function calling %%%%%%%%%%%%%
function dpdt = state( t,p)
smooth=1;   
vg=t;
k=10^-1;
window1=1-((2*p)-1).^(2*smooth);
%%% See, I just used the vgth value in below.which is global%%%%%%
%%%%The vgth vwas declared in main function and calculated in main function% 
dpdt=k*(vg+vgth)*window1;   

end

end

vgth 应该也可以在 ode 函数中访问,但在这里不起作用。如果我用一些常量替换 ode45 中的 global vgth,那么它工作正常。这意味着我的全局变量可访问性存在问题。

您或许可以使用以下内容

[t,p] = ode45(@(t,y) state(t,y,vgth), t, p0);

function dpdt = state( t,p, vgth)
smooth=1;   
vg=t;
k=10^-1;
window1=1-((2*p)-1).^(2*smooth);
dpdt=k*(vg+vgth)*window1; 

不需要 global 或类似的恶作剧。