Error calling global variable in function
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Manuel Fuelling
el 3 de Abr. de 2018
Respondida: Steven Lord
el 3 de Abr. de 2018
in my script i declare a global variable by
...Coeff(k,4)=B(3)-Taster_radius*norm(Coeff(k,1:3));
global Global_Coeff;
Global_Coeff=Coeff;
where Global_Coeff is a 4x4 matrix containing double values. So far so good. I now want to use these Global_Coeff in the following (different script):
lb=[1,1,1,1,1,1,1,1,1,1,1,1];
ub=[3,3,3,3,3,3,3,3,3,3,3,3];
rng default
x0 = [1,0.9,1.1,0.8,1.2,1.3,0.7,1.11,1.12,0.99,2.1,2.0];
[x,res] = lsqnonlin(@root2d,x0,lb,ub)
where the first four equations of the function root2d look like this:
function F = root2d(x)
F(1) = Global_Coeff(1,1)*x(1)+Global_Coeff(1,2)*x(2)+Global_Coeff(1,3)*x(3)+Global_Coeff(1,4);
F(2) = Global_Coeff(2,1)*x(4)+Global_Coeff(2,2)*x(5)+Global_Coeff(2,3)*x(6)+Global_Coeff(2,4);
F(3) = Global_Coeff(3,1)*x(7)+Global_Coeff(3,2)*x(8)+Global_Coeff(3,3)*x(9)+Global_Coeff(3,4);
F(4) = Global_Coeff(4,1)*x(10)+Global_Coeff(4,2)*x(11)+Global_Coeff(4,3)*x(12)+Global_Coeff(4,4);
...
end
This is the error message i get:
Undefined function or variable
'Global_Coeff'.
Error in root2d (line 6)
F(1) =
Global_Coeff(1,1)*x(1)+Global_Coeff(1,2)*x(2)+Global_Coeff(1,3)*x(3)+Global_Coeff(1,4);
Error in lsqnonlin (line 196)
initVals.F =
feval(funfcn{3},xCurrent,varargin{:});
Error in KMG2Koordinatenform (line 54)
[x,res] = lsqnonlin(@root2d,x0,lb,ub)
How do i pass my variables/4x4Matrix containg my double-values correctly, so my function root2d and the call lsqnonlin can use them?
0 comentarios
Respuesta aceptada
dpb
el 3 de Abr. de 2018
global Global_Coeff; has to be in every workspace and/or function that wants/needs access to the global variable; all you've done above is make it available in the base workspace of the script.
function F = root2d(x)
global Global_Coeff;
F(1) = Global_Coeff(1,1)*x(1)+Global_Coeff(1,2)*x(2...
...
0 comentarios
Más respuestas (1)
Steven Lord
el 3 de Abr. de 2018
You must declare a global variable as global in any function workspace in which you want to access it. So inside root2d you would need to declare it as global. But there are other more preferred approaches for passing extra parameters into the objective and/or constraint functions in an optimization function like lsqnonlin. See the "Passing Extra Parameters" page linked in the documentation for the lsqnonlin function for a description of other approaches and some notes on why global variables can be problematic.
0 comentarios
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!