我在使用 MATLAB python engine 时遇到问题.
我想从 Python 中获得 ODE 的近似解(使用类似于 MATLAB 中的 ode45
函数),但问题是 ODE 近似需要一个我似乎无法理解的 ODE 函数规范从 MATLAB Python 引擎创建。
它可以很好地从 Python 调用 MATLAB 函数,例如 isprime
,但似乎无法在 Python 中指定 MATLAB 函数。
因此我的问题是; 有什么方法可以从 Python 生成 MATLAB 函数代码,或者可以从 Python 指定 MATLAB 函数吗?
最佳答案
odefun
passed to ode45
, according to docs, has to be a function handle .
Solve the ODE
y' = 2t
Use a time interval of [0,5] and the initial condition y0 = 0.
tspan = [0 5];
y0 = 0;
[t,y] = ode45(@(t,y) 2*t, tspan, y0);
@(t,y) 2*t
返回匿名函数的函数句柄。
不幸的是,function handles are listed as one of datatypes unsupported in MATLAB <-> Python conversion :
Unsupported MATLAB Types The following MATLAB data types are not supported by the MATLAB Engine API for Python:
- Categorical array
- char array (M-by-N)
- Cell array (M-by-N)
- Function handle
- Sparse array
- Structure array
- Table
- MATLAB value objects (for a discussion of handle and value classes see Comparison of Handle and Value Classes)
- Non-MATLAB objects (such as Java® objects)
总而言之,似乎没有直接的方法。
潜在的解决方法可能涉及 engine.workspace
和 engine.eval
的某种组合,如 Use MATLAB Engine Workspace in Python 所示。示例。
使用 engine.eval
( first demo ) 的解决方法:
import matlab.engine
import matplotlib.pyplot as plt
e = matlab.engine.start_matlab()
tr, yr = e.eval('ode45(@(t,y) 2*t, [0 5], 0)', nargout=2)
plt.plot(tr, yr)
plt.show()
这样做可以避免通过 MATLAB/Python 屏障传递函数句柄。您传递字符串(字节)并允许 MATLAB 在那里对其进行评估。返回的是纯数值数组。之后,您可以对结果向量进行操作,例如绘制它们。
由于将参数作为文字传递很快就会变得很痛苦,可以使用 engine.workspace
来避免这种情况:
import matlab.engine
import matplotlib.pyplot as plt
e = matlab.engine.start_matlab()
e.workspace['tspan'] = matlab.double([0.0, 5.0])
e.workspace['y0'] = 0.0
tr, yr = e.eval('ode45(@(t,y) 2*t, tspan, y0)', nargout=2)
plt.plot(tr, yr)
plt.show()
关于python - 从 python 生成 MATLAB 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39556602/