Undefined function or variable in ode45

2 次查看(过去 30 天)
I have this differantial equation set.
k1, k2, k3, k4 are constants.
I need to find value of x and y at t=500.
I want to solve this set simultaneously. I wrote that code:
function da=fun(t,a)
k1=0.02; % day^-1 %constant for growth of rabbits
k2=0.00004; % (day*foxes)^-1 %constant for death of rabbits
k3=0.0004; % (day*rabbits)^-1 %constant for growth of
% foxes after eating rabbits
k4=0.04; % day^-1 %constant for death of foxes
x=a(1,:);
y=a(2,:);
da(1,:)=k1*x-k2*x*y;
da(2,:)=k3*x*y-k4*y;
clear all
timerange=[0 500];
initial=[500 200];
[t,a]=ODE45(@fun,timerange,initial);
When i run, i get "Undefined function or variable 't'." error.
Can anyone help?
  2 个评论
Cedric
Cedric 2015-2-15
编辑:Cedric 2015-2-15
Just to be sure (because I formatted your question this way), the lines
function da=fun(t,a)
to
da(2,:)=k3*x*y-k4*y;
(note that in your question, it was initially written a(2,:)=.. and not da(2,:)=..) are in a separate file named fun.m, and from
clear all
to the end, this is a separate file/script (?)
Ugur Bozuyuk
Ugur Bozuyuk 2015-2-15
编辑:Ugur Bozuyuk 2015-2-15
I deleted "clear all". It still doesn't work. Can you be more spesific?

请先登录,再进行评论。

采纳的回答

Cedric
Cedric 2015-2-15
编辑:Cedric 2015-2-15
You cannot have all these lines of code in the same file. You must have two M-files, one named fun.m which contains
function da=fun(t,a)
k1=0.02; % day^-1 %constant for growth of rabbits
k2=0.00004; % (day*foxes)^-1 %constant for death of rabbits
k3=0.0004; % (day*rabbits)^-1 %constant for growth of
% foxes after eating rabbits
k4=0.04; % day^-1 %constant for death of foxes
x=a(1,:);
y=a(2,:);
da(1,:)=k1*x-k2*x*y;
da(2,:)=k3*x*y-k4*y;
And the other named as you prefer, which contains:
clear all
timerange=[0 500];
initial=[500 200];
[t,a]=ode45(@fun,timerange,initial);
Note that MATLAB is case sensitive, so you have to call ode45 and not ODE45 (beware the forum for that, as we often capitalize function names outside of code blocks, to differentiate them from the rest of the text).
I tested and I am attaching a zip file with the two files that you should have. You can rename main.n into whatever you want, but fun.m cannot be changed, as the file name must match the function name (or you can change both the file name and the function name).
%

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 App Building 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by