从MATLAB调用Python函数
我需要从MATLAB调用Python函数。我怎样才能做到这一点呢?您可以,但与将结果转储到文件相比,这可能需要很多工作 您可以使用调用Python中的MATLAB函数。除此之外,它还具有多个MATLAB复制函数从MATLAB调用Python函数,python,matlab,language-interoperability,Python,Matlab,Language Interoperability,我需要从MATLAB调用Python函数。我怎样才能做到这一点呢?您可以,但与将结果转储到文件相比,这可能需要很多工作 您可以使用调用Python中的MATLAB函数。除此之外,它还具有多个MATLAB复制函数 但是,如果需要从MATLAB运行Python脚本,可以尝试运行命令来运行脚本,并将结果存储在文件中,然后在MATLAB中读取。我的系统也有类似的要求,这就是我的解决方案: 在MATLAB中有一个名为perl.m的函数,它允许您从MATLAB调用perl脚本。根据您使用的版本,它将位于以下
但是,如果需要从MATLAB运行Python脚本,可以尝试运行命令来运行脚本,并将结果存储在文件中,然后在MATLAB中读取。我的系统也有类似的要求,这就是我的解决方案: 在MATLAB中有一个名为perl.m的函数,它允许您从MATLAB调用perl脚本。根据您使用的版本,它将位于以下位置
C:\Program Files\MATLAB\R2008a\toolbox\matlab\general\perl.m
创建一个名为python.m的副本,这是一个用python快速搜索和替换perl的方法,请仔细检查它设置的命令路径,以指向您的python安装。现在,您应该能够从MATLAB运行python脚本
示例
python中的一个简单的平方函数保存为“sqd.py”,如果我做得好,自然会在测试输入参数、有效数字等时进行一些检查
import sys
def squared(x):
y = x * x
return y
if __name__ == '__main__':
x = float(sys.argv[1])
sys.stdout.write(str(squared(x)))
然后在MATLAB中
>> r=python('sqd.py','3.5')
r =
12.25
>> r=python('sqd.py','5')
r =
25.0
>>
因为Python是一种更好的粘合语言,所以从Python调用程序部分可能更容易,而不是从Python调用程序部分
查看。由于与Java无缝集成,您可以使用编写脚本并从MATLAB调用它(您可能需要添加一个瘦的纯JKava包装器来实际调用Jython代码)。我从未尝试过它,但我不明白它为什么不起作用。我已经将
perl.m
修改为python.m
,并附上此文件以供其他人参考,但我似乎无法从python脚本中获得任何返回到MATLAB变量的输出:(
这是我的M文件;注意,在我的代码中,我直接指向Python文件夹,C:\python27\u 64
,这将在您的系统上发生变化
function [result status] = python(varargin)
cmdString = '';
for i = 1:nargin
thisArg = varargin{i};
if isempty(thisArg) || ~ischar(thisArg)
error('MATLAB:python:InputsMustBeStrings', 'All input arguments must be valid strings.');
end
if i==1
if exist(thisArg, 'file')==2
if isempty(dir(thisArg))
thisArg = which(thisArg);
end
else
error('MATLAB:python:FileNotFound', 'Unable to find Python file: %s', thisArg);
end
end
if any(thisArg == ' ')
thisArg = ['"', thisArg, '"'];
end
cmdString = [cmdString, ' ', thisArg];
end
errTxtNoPython = 'Unable to find Python executable.';
if isempty(cmdString)
error('MATLAB:python:NoPythonCommand', 'No python command specified');
elseif ispc
pythonCmd = 'C:\python27_64';
cmdString = ['python' cmdString];
pythonCmd = ['set PATH=',pythonCmd, ';%PATH%&' cmdString];
[status, result] = dos(pythonCmd)
else
[status ignore] = unix('which python'); %#ok
if (status == 0)
cmdString = ['python', cmdString];
[status, result] = unix(cmdString);
else
error('MATLAB:python:NoExecutable', errTxtNoPython);
end
end
if nargout < 2 && status~=0
error('MATLAB:python:ExecutionError', ...
'System error: %sCommand executed: %s', result, cmdString);
end
function[结果状态]=python(varargn)
cmdString='';
对于i=1:nargin
thisArg=varargin{i};
如果isempty(thisArg)| | ~ischar(thisArg)
错误('MATLAB:python:InputsMustBeStrings','所有输入参数必须是有效字符串');
结束
如果i==1
如果存在(thisArg,'file')==2
如果为空(dir(thisArg))
thisArg=哪个(thisArg);
结束
其他的
错误('MATLAB:python:FileNotFound','找不到python文件:%s',thisArg);
结束
结束
如果有(thisArg='')
thisArg=['”,thisArg''”;
结束
cmdString=[cmdString',thisArg];
结束
errTxtNoPython='无法找到Python可执行文件';
如果为空(cmdString)
错误('MATLAB:python:NoPythonCommand','No-python命令未指定');
elseif ispc
pythonCmd='C:\python27_64';
cmdString=['python'cmdString];
pythonCmd=['set PATH=',pythonCmd',;%PATH%&'cmdString];
[状态,结果]=dos(pythonCmd)
其他的
[status ignore]=unix('which python');%#确定
如果(状态==0)
cmdString=['python',cmdString];
[状态,结果]=unix(cmdString);
其他的
错误('MATLAB:python:NoExecutable',errTxtNoPython);
结束
结束
如果nargout<2&&status~=0
错误('MATLAB:python:ExecutionError'。。。
'系统错误:%s执行的命令:%s',结果,cmdString);
结束
编辑:
解决了我的问题原始的perl.m指向MATLAB文件夹中的一个安装,方法是更新PATH,然后调用perl。上面的函数指向我的Python安装。当我调用
function.py
文件时,它位于不同的目录中,并调用该目录中的其他文件。这些文件在PATH,我必须轻松地将Python文件安装到Python发行版中。最简单的方法是使用的函数
因此,基本上,您可以在MATLAB上执行Python函数,就像在命令提示符(Windows)或shell(Linux)上一样:
以上内容仅用于运行Python文件。如果您想运行Python函数(并为其提供一些参数),则需要以下内容:
system('python pythonfile.py argument')
举一个具体的例子,以Adrian对这个问题的回答中的Python代码为例,将其保存到一个Python文件中,即test.py
。然后将该文件放在MATLAB目录中,并在MATLAB上运行以下命令:
system('python test.py 2')
您将得到输出4或2^2
注意:MATLAB在当前的MATLAB目录中查找您使用system
命令指定的任何Python文件
这可能是解决问题的最简单方法,因为您只需使用MATLAB中的现有函数进行投标。这似乎是将函数从“隧道”到“隧道”的合适方法:
最大的优点是,您可以使用它处理Ndarray,这在前面建议的标准程序输出中是不可能的。(请纠正我,如果您认为这是错误的-这将为我节省很多麻烦:-)尝试使用此MEX文件从MATLAB实际调用Python,而不是像其他人建议的那样。它提供了相当不错的集成: 您可以轻松地执行以下操作:
[X,Y]=meshgrid(-10:0.1:10,-10:0.1:10);
Z=sin(X)+cos(Y);
py_export('X','Y','Z')
stmt = sprintf(['import matplotlib\n' ...
'matplotlib.use(''Qt4Agg'')\n' ...
'import matplotlib.pyplot as plt\n' ...
'from mpl_toolkits.mplot3d import axes3d\n' ...
'f=plt.figure()\n' ...
'ax=f.gca(projection=''3d'')\n' ...
'cset=ax.plot_surface(X,Y,Z)\n' ...
'ax.clabel(cset,fontsize=9,inline=1)\n' ...
'plt.show()']);
py('eval', stmt);
正如@dgorissen所说,Jython是最简单的解决方案 只需从中安装Jython 然后: 有关一些示例,请参见 注意:我从来没有真正与Jython合作过,而且似乎人们从CPython知道的标准库并没有在Jython中完全实现 我测试的小示例工作得很好,但您可能会发现必须将Python代码目录预先添加到
sys.path
关于的system()的一个鲜为人知的事实
函数:在unixoid系统上,它使用启动MATLAB时环境变量SHELL
或MATLAB\u SHELL
中给出的任何解释器。所以如果你从MATLAB开始
SHELL='/usr/bin/python' matlab
任何后续的
system()
调用都将使用而不是默认的shell作为解释器。使用Matlab 2014b python libra
javaaddpath('/path-to-your-jython-installation/jython.jar')
import org.python.util.PythonInterpreter;
python = PythonInterpreter; %# takes a long time to load!
python.exec('import some_module');
python.exec('result = some_module.run_something()');
result = python.get('result');
SHELL='/usr/bin/python' matlab
>> wrapped = py.textwrap.wrap("example")
wrapped =
Python list with no properties.
['example']
result = py.module_name.function_name(parameter1);