![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/310349/image.png)
ode4 gives variable undefined error
3 次查看(过去 30 天)
显示 更早的评论
I am trying to use a fixed step solver, such as ODE4 to calculate a value after a fixed time step, however, I am getting stuck on a very basic point. I have to pass F to the ode solver however, obviously because it is an ode, I have the variable that I need to find in F so it is giving me " variable undefined" error. This error is obvious to me but is there a way around it?
I am using the following function from mathworks - ode4 . Please find the code in the functions tab.
And my function calling statement is -
t = linspace(1,10)
vp(1) = 5 %some constant that changes in the loop below
for i = 1: length(t)
v = ode4((v - vf), t(i), 1, t(i+1),vp(1));
vp(1) = 45; % some updated value ( I've chosen a random number for the time being)
end
%error displayed
% -->> Undefined function or variable 'v'.
0 个评论
采纳的回答
Bjorn Gustavsson
2020-6-5
First of all you have to make sure that you call ode4 with the inputs it expects. In your call you do not have any function. According to the ode4 information it expects a call looking like this:
ode4(F,t0,h,tfinal,y0)
Inside ode4 you will see that F is used like this:
s1 = F(t,y);
This means that F has to be a function of t and y, and those 2 variable only. For example:
F = @(t,y) 2*exp(-(y-0.32*t).^2/4)
Then you can integrate the ode:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/310349/image.png)
from 0 to 12 in steps of 1/4 something like this:
Y0to12 = ode4(F,0,1/4,12,0);
2 个评论
Bjorn Gustavsson
2020-6-5
This depends on whether vf is constant during your period of integration or if it varies (and if it varies, then it depends on how it varies.).
1: If vf is constant you simply pass its value on to the function F, something like this:
Y0to12 = ode4(@(t,y) F(t,y,vf),0,1/4,12,0);
where the definition of F now has to be modified:
F = @(t,y,vf) 2*exp(-(y-0.32*t).^2/vf^2)
If it varies smothly with time in a known way it is best to write vf as a function of t:
vf = @(t) 1+sin(t).^2*0.95;
If you know vf at a number of discrete points in time and think that it varies smothly in time then you can build the vf-function with interp1:
vf = @(t) interp1(t_fixed,vf_fixed,t,'pchip');
If it varies more randomly you will have to deal with that too.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Ordinary Differential Equations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!