【发布时间】:2018-11-02 23:23:35
【问题描述】:
我正在尝试从 python 运行 MATLAB 函数。我正在关注 MathWorks Tutorial。在该教程中,他们指定可以在 python 中查看 MATLAB 脚本的输出。他们给出的例子有以下代码
% This code is in a MATLAB script called triarea.m
b = 5;
h = 3;
a = 0.5*(b.* h) % Notice that there is no semicolon to suppress output.
python部分:
import matlab.engine
eng = matlab.engine.start_matlab()
eng.triarea(nargout=0)
python 脚本应该打印出来
a =
7.5000
当它作为普通的 python 脚本运行时(例如,使用 PyCharm),这非常有效。但是,当使用 Jupyter notebook 运行此 python 代码时,不会打印任何内容。
使用 Jupyter notebook 运行 python 代码时如何得到正确的输出?
到目前为止,我已经尝试指定标准输出(如here 中所建议的那样)。即我的python代码现在读取
import io
out = io.StringIO()
eng.triareaf(nargout=0, stdout=out)
但是,我仍然无法获得正确的输出。我正在使用 Python 3.5、MATLAB R2017a、Jupyter 版本 4.4.0 和 Windows 10。
【问题讨论】:
-
不知道为什么会这样。大概他们就是这样制作的。顺便说一句,linked MATLAB 文档页面中的第二个示例可以满足您的需求
-
它并不完全符合我的要求。第二个示例要求 Matlab 函数返回我要打印的值。这也意味着我看不到 Matlab 脚本的输出,因为脚本没有返回值。
标签: python python-3.x matlab jupyter-notebook jupyter