内插后用ode45求解ODE [英] Solving an ODE with ode45 after interpolating
问题描述
我正在使用以下代码,找不到错误的地方:
I am working with the following code and can't find what is wrong:
xx = 0:1/50:1;
v = 3.*exp(-xx)-0.4*xx;
xq = xx;
vq = @(xq) interp1(xx,v,xq);
tspan = 0:1/50:1;
x0 = 3;
[~, y2] = ode45(@(t,x)vq(x), tspan, x0);
我知道了y2 = [3;NAN;NAN;NAN,.....]
.但是,当我在调用ode45
之前绘制两个方程式时,我发现它们相等,这不足为奇.
I get that y2 = [3;NAN;NAN;NAN,.....]
. Yet, when I plot both equations before calling ode45
, I get that they are equal, which is not a surprise.
当我计算时:
f = @(t,r) 3.*exp(-r)-0.4*r;
[~, y] = ode45(f,tspan,x0);
它工作正常.但是我需要证明,如果插值,我可以获得相同的结果.为什么这样不起作用?
it works fine. But I need to show that I can get the same results if I interpolate. Why is that not working?
推荐答案
You get NaN
because that is the default returned by interp1
for values outside of the interval spanned by xx
. In you case, xx
only varies from 0
to 1
. But your initial condition is at 3
. If you're going to use interpolation you need start inside of the interval defined by your data and make sure you stay there. For example, if you simply change your initial condition:
xx = 0:1/50:1;
v = 3.*exp(-xx)-0.4*xx;
xq = xx;
vq = @(xq) interp1(xx,v,xq);
tspan = 0:1/50:1;
x0 = 0.1;
[t, y2] = ode45(@(t,x)vq(x), tspan, x0);
f = @(t,r) 3.*exp(-r)-0.4*r;
[t, y] = ode45(f,tspan,x0);
figure;
subplot(211)
plot(t,y,'b',t,y2,'r--')
subplot(212)
plot(t,abs(y-y2))
xlabel('t')
ylabel('Absolute Error')
即使在这种初始条件下,由于指数增长,系统状态在特定点也会离开您的[0,1]间隔,并且y2
将变为NaN
.如果愿意,可以告诉interp1
使用实际推断但是.
Even with this initial condition, because of the exponential growth, at a certain point the state of the system leaves your [0, 1] interval and y2
will become NaN
. You can tell interp1
to use actual extrapolation if you prefer though.
这篇关于内插后用ode45求解ODE的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!