用Python语言在MATLAB中模拟ode45函数

2024-04-28 20:01:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何将MATLAB函数ode45导出到python。根据文件规定如下:

 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不同。


Tags: 文件函数importnumpyreturndefasnp
2条回答

integrate.ode的接口不像更简单的方法odeint那样直观,但是它不支持选择ODE积分器。主要的区别是ode不为您运行循环;如果您需要在一堆点上找到一个解决方案,则必须说明在哪些点上,并一次计算一个点。

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()

solution

正如@LutzL所提到的,您可以使用较新的API ^{}

results = solve_ivp(obj_func, t_span, y0, t_eval = time_series)

如果没有指定t_eval,那么每个时间戳就没有一条记录,这是我假设的大多数情况。

另一个注意事项是,对于^{}和通常是其他积分器,输出数组是[len(time), len(states)]形状的ndarray,但是对于solve_ivp,输出是一维ndarray的list(length of state vector)(其长度等于t_eval)。

所以如果你想要相同的顺序你必须合并它。你可以这样做:

Y =results
merged = np.hstack([i.reshape(-1,1) for i in Y.y])

首先,需要对其进行整形,使其成为一个[n,1]数组,并将其水平合并。 希望这有帮助!

相关问题 更多 >