python - 从 python 生成 MATLAB 代码

标签 python matlab python-3.x

我在使用 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.workspaceengine.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 在那里对其进行评估。返回的是纯数值数组。之后,您可以对结果向量进行操作,例如绘制它们。

Matplotlib result

由于将参数作为文字传递很快就会变得很痛苦,可以使用 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/

相关文章:

python - nose.collector 在哪里寻找测试?

python - 如何在pandas read_Sql中复制并粘贴sql查询

python - 具有多个 URL 模式和可选参数的相同 View

Matlab:用不包括自身的行的最小值替换矩阵中的元素

python - celery :如何只为最后一个链节存储结果?

python - 即使在关闭 pyqt 应用程序后网络摄像头实例也不会被释放

python - 使用 Python 和 Pandas 拆分文本文件中的数据

python - Google App Engine 有效负载对象

matlab - 基于向量创建逐行增加差异的矩阵

matlab - 如何在 Matlab 中绘制圆?