Global variable not seen by function: the function creates a new empty variable
Afficher commentaires plus anciens
Hi everyone. I have an script that defines a global variable and a function defining a system of ODEs, for example
Script:
clc, clear
global T
%some lines
T=something;
[t,x]=ode23s(@func,time,x0)
%some lines
function
function dx=func(t,x)
global T
k1=5.35e18*exp(-15700/T);
k2=5.35e18*exp(-15700/T);
k3=75.45e18*exp(-15700/T);
r1= k1*x(1)*x(2))-k3*x(3);
r2=k2*x(2)*x(3);
dx=[-r1; -(r1-r2); r1-r2; r2];
The script and function are in separate files, same folder. The error message says
Error using /
Matrix dimensions must agree.
Indicating that the variable T in the function func workspace appears as empty [] Why is this, and how can I pass this T to that function? I do know functions can pass arguments but in this case it is not directly but ode23s is who's calling @func. Thanks in advance.
1 commentaire
This is why the MATLAB documentation states "Global variables can be troublesome, so it is better to avoid using them": because globals are buggy and hard to debug. Much better is to use an anonymous function, exactly as the MATLAB documentation recommends:
Réponse acceptée
Plus de réponses (1)
Jan
le 5 Juil 2017
While I agree, that globals should be avoided, you code should work:
function main
global T
T = something
...
function sub
global T
a = 1.23 / T
If you get the error according the size of T, this means, that something replies the empty matrix. If you use the recommended anonymous function (see also: http://www.mathworks.com/matlabcentral/answers/1971), this problem will still exist: There is a bug in "something".
Catégories
En savoir plus sur Programming dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!