在Python中从MATLAB模仿ode45函数 [英] Imitate ode45 function from MATLAB in Python
本文介绍了在Python中从MATLAB模仿ode45函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何将MATLAB函数ode45导出到python.根据文档应如下:
I am wondering how to export MATLAB function ode45 to python. According to the documentation is should be as follows:
MATLAB: [t,y]=ode45(@vdp1,[0 20],[2 0]);
Python: import numpy as np
def vdp1(t,y):
dydt= np.array([y[1], (1-y[0]**2)*y[1]-y[0]])
return dydt
import scipy integrate
l=scipy.integrate.ode(vdp1([0,20],[2,0])).set_integrator("dopri5")
结果是完全不同的,Matlab返回的尺寸不同于Python.
The results are completely different, Matlab returns different dimensions than Python.
推荐答案
odeint ,但是它不支持选择ODE集成器.主要区别在于ode
不会为您运行循环.如果您需要一堆解决方案,则必须说出什么位置,然后一次计算一个点.
The interface of integrate.ode is not as intuitive as of a simpler method odeint which, however, does not support choosing an ODE integrator. The main difference is that ode
does not run a loop for you; if you need a solution at a bunch of points, you have to say at what points, and compute it one point at a time.
import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt
def vdp1(t, y):
return np.array([y[1], (1 - y[0]**2)*y[1] - y[0]])
t0, t1 = 0, 20 # start and end
t = np.linspace(t0, t1, 100) # the points of evaluation of solution
y0 = [2, 0] # initial value
y = np.zeros((len(t), len(y0))) # array for solution
y[0, :] = y0
r = integrate.ode(vdp1).set_integrator("dopri5") # choice of method
r.set_initial_value(y0, t0) # initial values
for i in range(1, t.size):
y[i, :] = r.integrate(t[i]) # get one more value, add it to the array
if not r.successful():
raise RuntimeError("Could not integrate")
plt.plot(t, y)
plt.show()
这篇关于在Python中从MATLAB模仿ode45函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文