Octave中函数为运行时的全局变量和错误

Global variable and error when the function is running in Octave

在 Octave 环境中使用 ode45 求解器编写(以编程方式实现)求解刚性方程 eq = -lambda * (y-sin (x)) 的问题。

有代码

lambda=10#Global variable for function

function slv=fi(x)#Equation solution
  C=1+(lambda/(1+pow2(lambda)));
  slv=C*exp(-lambda*x)-(lambda/(1+pow2(lambda)))*(-lambda*sin(x)+cos(x));
end

#The initial function of the equation
function y=g(t,x)
  y=-lambda*(x-sin(t));–1 ERROR
end

%Determination of parameters for controlling the course of the equation
optio=odeset("RelTol",1e-5,"AbsTol",1e-5,'InitialStep',0.025,'MaxStep',0.1);


[XX,YY]=ode45(@g,[0 0.25],2,optio); - 2 ERROR

#Exact solution
x1=0:0.05:0.25;
y1=fi(x1);

%Function solution graph with ode45 and exact solution
plot(x1,y1,'-g:exact solution;',XX,YY,'*b;ode45;');
grid on;

但是有一些错误:

lambda = 10
error: 'lambda' undefined near line 11, column 11
error: called from
    g at line 11 column 4
    runge_kutta_45_dorpri at line 103 column 12
    integrate_adaptive at line 135 column 39
    ode45 at line 241 column 12
    LabWork6 at line 18 column 8

由于函数中的 lambda 变量,错误移到了程序的另一部分。 声明 lambda 时我做错了什么?

脚本中 'global' 范围内的变量在函数中是不可见的,即使是在命令行而不是它们自己的文件中定义的,因为这是正确的方法。

如果你仔细想想,这是有道理的,因为命令行函数只是方便的语法,文件定义的函数不知道其他脚本在某处定义了变量,除非你使用 global 关键字来告诉它有关该变量的信息。

因此,要么将 lambda 声明为函数外部和内部的 global,要么简单地将整个脚本包装在一个函数中,然后允许 'nested' 函数到 see/inherit 父函数变量。