Global variable not seen by function: the function creates a new empty variable
110 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Adam
2017-7-5
Define your function as:
function dx=func(t,x,T)
...
Use it as:
T=something;
[t,x]=ode23s(@(t,x) func(t,x,T),time,x0)
I suspect you will still have your error as it is probably a dimension issue as the error indicates, but the debugger will tell you this instantly. Certainly it is always plenty possible that global variables can lead to a mess though. I have no idea if they can be picked up inside a file called by ode23s and would never wish to try!
更多回答(1 个)
Jan
2017-7-5
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".
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!