Search code examples
octavegnu

Global variable and error when the function is running in Octave


Program (programmatically implement) the problem of solving the rigid equation eq = -lambda * (y-sin (x)) using the ode45 solver in the Octave environment.

enter image description here

There is code

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;

But there are some errors:

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

Due to the lambda variable in the function, the error moved to another part of the program. What did I do wrong when declaring a lambda?


Solution

  • Variables at 'global' scope in a script are not visible from within functions, even if defined on the command-line instead of their own file, as it the proper way.

    This makes sense if you think about it, because command-line functions are just convenience syntax, and a file-defined function would have no idea that some other script defines a variable somewhere, unless you use the global keyword to tell it about that variable.

    So either declare lambda as global both outside and inside your function, or simply wrap your entire script inside a function, which then allows 'nested' functions to see/inherit parent-function variables.