从 MATLAB 调用 Python 函数

发布于 2024-08-11 02:49:07 字数 38 浏览 5 评论 0原文

我需要从 MATLAB 调用 Python 函数。我该怎么做?

I need to call a Python function from MATLAB. how can I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

哽咽笑 2024-08-18 02:49:07

我对我的系统有类似的要求,这就是我的解决方案:

在 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
>>

I had a similar requirement on my system and this was my solution:

In MATLAB there is a function called perl.m, which allows you to call perl scripts from MATLAB. Depending on which version you are using it will be located somewhere like

C:\Program Files\MATLAB\R2008a\toolbox\matlab\general\perl.m

Create a copy called python.m, a quick search and replace of perl with python, double check the command path it sets up to point to your installation of python. You should now be able to run python scripts from MATLAB.

Example

A simple squared function in python saved as "sqd.py", naturally if I was doing this properly I'd have a few checks in testing input arguments, valid numbers etc.

import sys

def squared(x):
    y = x * x
    return y

if __name__ == '__main__':
    x = float(sys.argv[1])
    sys.stdout.write(str(squared(x)))

Then in MATLAB

>> r=python('sqd.py','3.5')
r =
12.25
>> r=python('sqd.py','5')
r =
25.0
>>
多情癖 2024-08-18 02:49:07

使用 Matlab 2014b,可以直接从 matlab 调用 python 库。前缀 py. 添加到所有数据包名称中:

>> wrapped = py.textwrap.wrap("example")

wrapped = 

  Python list with no properties.

    ['example']

With Matlab 2014b python libraries can be called directly from matlab. A prefix py. is added to all packet names:

>> wrapped = py.textwrap.wrap("example")

wrapped = 

  Python list with no properties.

    ['example']
聆听风音 2024-08-18 02:49:07

尝试使用此 MEX 文件实际从 MATLAB 调用 Python,而不是像其他人建议的那样相反。它提供了相当不错的集成: http://algoholic.eu/matpy/

您可以轻松地执行以下操作:

[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);

Try this MEX file for ACTUALLY calling Python from MATLAB not the other way around as others suggest. It provides fairly decent integration : http://algoholic.eu/matpy/

You can do something like this easily:

[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);
香橙ぽ 2024-08-18 02:49:07

您可以将 Python 脚本嵌入到 C 程序中,然后使用 MATLAB MEX C 程序,但这与将结果转储到文件相比可能需要大量工作。

您可以使用 PyMat 在 Python 中调用 MATLAB 函数。除此之外,SciPy 有几个 MATLAB 重复函数。

但如果您需要从 MATLAB 运行 Python 脚本,您可以尝试运行 system 命令运行脚本并将结果存储在文件中,并稍后在 MATLAB 中读取。

You could embed your Python script in a C program and then MEX the C program with MATLAB but that might be a lot of work compared dumping the results to a file.

You can call MATLAB functions in Python using PyMat. Apart from that, SciPy has several MATLAB duplicate functions.

But if you need to run Python scripts from MATLAB, you can try running system commands to run the script and store the results in a file and read it later in MATLAB.

天赋异禀 2024-08-18 02:49:07

正如 @dgorissen 所说,Jython 是最简单的解决方案。

只需从主页安装 Jython。

然后:

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');

请参阅文档了解一些示例。

请注意:我从未真正使用过 Jython,并且似乎从 CPython 中了解到的标准库并未在 Jython 中完全实现!

我测试的小示例运行得很好,但您可能会发现必须将 Python 代码目录添加到 sys.path 中。

As @dgorissen said, Jython is the easiest solution.

Just install Jython from the homepage.

Then:

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');

See the documentation for some examples.

Beware: I never actually worked with Jython and it seems that the standard library one may know from CPython is not fully implemented in Jython!

Small examples I tested worked just fine, but you may find that you have to prepend your Python code directory to sys.path.

烟燃烟灭 2024-08-18 02:49:07

最简单的方法是使用 MATLAB系统 函数。

基本上,您可以在 MATLAB 上执行 Python 函数,就像在命令提示符 (Windows) 或 shell (Linux) 上执行一样:

system('python pythonfile.py')

以上仅是运行 Python 文件。如果你想运行一个Python函数(并给它一些参数),那么你需要类似的东西:

system('python pythonfile.py argument')

举个具体的例子,取Adrian对此问题的回答中的Python代码,并将其保存到一个Python文件中,即<代码>测试.py。然后将此文件放入 MATLAB 目录中,并在 MATLAB 上运行以下命令:

system('python test.py 2')

您将得到输出 4 或 2^2。

注意:MATLAB 在当前 MATLAB 目录中查找您使用 system 命令指定的任何 Python 文件。

这可能是解决问题的最简单方法,因为您只需使用 MATLAB 中的现有函数即可完成您的任务。

The simplest way to do this is to use MATLAB's system function.

So basically, you would execute a Python function on MATLAB as you would do on the command prompt (Windows), or shell (Linux):

system('python pythonfile.py')

The above is for simply running a Python file. If you wanted to run a Python function (and give it some arguments), then you would need something like:

system('python pythonfile.py argument')

For a concrete example, take the Python code in Adrian's answer to this question, and save it to a Python file, that is test.py. Then place this file in your MATLAB directory and run the following command on MATLAB:

system('python test.py 2')

And you will get as your output 4 or 2^2.

Note: MATLAB looks in the current MATLAB directory for whatever Python file you specify with the system command.

This is probably the simplest way to solve your problem, as you simply use an existing function in MATLAB to do your bidding.

心房的律动 2024-08-18 02:49:07

从Matlab 2014b开始可以直接调用Python函数。
使用前缀 py,然后是模块名称,最后是函数名称,如下所示:

result = py.module_name.function_name(argument1, argument2, ...);

如果您位于与 Python 脚本不同的工作目录中,请确保在从 Matlab 调用时将脚本添加到 Python 搜索路径。


简介

下面的源代码解释了如何从 Matlab 脚本调用 Python 模块中的函数。

假设已安装 MATLAB 和 Python(在此特定示例中还安装了 NumPy)。

探索我登陆的主题 此链接MathWorks 网站上的(MATLAB 2014b 发行说明)表明可以从 Matlab R2014b 开始。

说明

在下面的示例中,假设当前工作目录将具有以下结构:

our_module
  |
  +-> our_script.py
matlab_scripts
  |
  +-> matlab_script.m

从一个简单的脚本 our_module/our_script.py 开始:

import numpy

def our_function(text):
    print('%s %f' % (text, numpy.nan))

它有一个函数,用于打印作为参数传递给它的字符串,后跟 NaN(非数字)值。

将其保存在自己的目录our_module中。

接下来,转到 Matlab 并导航到 Python 模块 (our_module) 所在的当前工作目录。

使用以下语句从 Python 模块调用该函数:

py.our_module.our_script.our_function('Hello')

这将产生预期结果:

>> py.our_module.our_script.our_function('Hello')
Hello nan
>>

但是,matlab_scripts 目录中会出现一个 matlab_script.m 文件(在 < em>our_module 目录)仅使用上述语句将导致以下结果:

>> matlab_script
Undefined variable "py" or class "py.our_module.our_script.our_function".

Error in matlab_script (line 1)
py.our_module.our_script.our_function('Hello')
>>

在寻找解决方案时,我发现了 页面,标题为未定义的变量“py”或函数“py.command”,这有助于解决此问题错误。

假设脚本中没有拼写错误,它建议将基本目录添加到 Python 的搜索路径中。

因此,Matlab脚本的正确内容应该是:

[own_path, ~, ~] = fileparts(mfilename('fullpath'));
module_path = fullfile(own_path, '..');
python_path = py.sys.path;
if count(python_path, module_path) == 0
    insert(python_path, int32(0), module_path);
end
py.our_module.our_script.our_function('Hello')

获取Python模块的位置,找到该模块的基本路径,访问Python搜索路径,检查基本路径是否已包含,否则插入。

运行更正后的脚本将产生与以前相同的预期输出。

这里是另一个有用的链接,可帮助您继续前进。

Starting from Matlab 2014b Python functions can be called directly.
Use prefix py, then module name, and finally function name like so:

result = py.module_name.function_name(argument1, argument2, ...);

Make sure to add the script to the Python search path when calling from Matlab if you are in a different working directory than that of the Python script.


Introduction

The source code below explains how to call a function from a Python module from a Matlab script.

It is assumed that MATLAB and Python are already installed (along with NumPy in this particular example).

Exploring the topic I landed on this link (MATLAB 2014b Release Notes) on the MathWorks website which indicated that it is possible starting from Matlab R2014b.

Instructions

In the example below it is assumed the current working directory will have the following structure:

our_module
  |
  +-> our_script.py
matlab_scripts
  |
  +-> matlab_script.m

Start with a simple script our_module/our_script.py:

import numpy

def our_function(text):
    print('%s %f' % (text, numpy.nan))

It has one function which prints the string passed to it as a parameter, followed by NaN (not-a-number) value.

Keep it in its own directory our_module.

Next, go to Matlab and navigate to the current working directory where the Python module (our_module) is located.

Call the function from the Python module with the following statement:

py.our_module.our_script.our_function('Hello')

This will have the expected outcome:

>> py.our_module.our_script.our_function('Hello')
Hello nan
>>

However, a matlab_script.m file in a matlab_scripts directory (created next to the our_module directory) with only the above statement will result in the following outcome:

>> matlab_script
Undefined variable "py" or class "py.our_module.our_script.our_function".

Error in matlab_script (line 1)
py.our_module.our_script.our_function('Hello')
>>

Looking for the solution I found a page entitled Undefined variable "py" or function "py.command" which helped to troubleshoot this error.

Assuming there is no typo in the script it recommends adding the base directory to Python's search path.

Therefore, the correct content of the Matlab script should be:

[own_path, ~, ~] = fileparts(mfilename('fullpath'));
module_path = fullfile(own_path, '..');
python_path = py.sys.path;
if count(python_path, module_path) == 0
    insert(python_path, int32(0), module_path);
end
py.our_module.our_script.our_function('Hello')

It obtains the location of the Python module, finds the base path of that module, accesses the Python search path, checks if the base path is already included and inserts it otherwise.

Running the corrected script will result in the same expected output as before.

Here is another helpful link to get you going.

何其悲哀 2024-08-18 02:49:07

我已将 perl.m 改编为 python.m 并附上此内容以供其他人参考,但我似乎无法从 Python 脚本中获得任何输出返回到 MATLAB 变量:(

这是我的 M 文件;请注意,我直接指向代码中的 Python 文件夹 C:\python27_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

编辑:

已工作解决我的问题原始 perl.m 通过更新 指向 MATLAB 文件夹中的 Perl 安装>PATH 然后调用 Perl。上面的函数指向我的 Python 安装。当我调用我的 function.py 文件时,它位于不同的目录中并调用该目录中的其他文件。其中没有反映在 PATH 中,我必须将我的 Python 文件轻松安装到我的 Python 发行版中。

I've adapted the perl.m to python.m and attached this for reference for others, but I can't seem to get any output from the Python scripts to be returned to the MATLAB variable :(

Here is my M-file; note I point directly to the Python folder, C:\python27_64, in my code, and this would change on your system.

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

EDIT :

Worked out my problem the original perl.m points to a Perl installation in the MATLAB folder by updating PATH then calling Perl. The function above points to my Python install. When I called my function.py file, it was in a different directory and called other files in that directory. These where not reflected in the PATH, and I had to easy_install my Python files into my Python distribution.

仄言 2024-08-18 02:49:07

关于 记录 的鲜为人知的事实a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow">MATLAB 的 system() 函数:在 unixoid 系统上它使用任何解释器在启动 MATLAB 时在环境变量 SHELLMATLAB_SHELL 中给出。因此,如果您通过

SHELL='/usr/bin/python' matlab

任何后续 system() 调用启动 MATLAB,将使用 Python 而不是默认的 shell 作为解释器。

A little known (and little documented) fact about MATLAB's system() function: On unixoid systems it uses whatever interpreter is given in the environment variable SHELL or MATLAB_SHELL at the time of starting MATLAB. So if you start MATLAB with

SHELL='/usr/bin/python' matlab

any subsequent system() calls will use Python instead of your default shell as an interpreter.

莳間冲淡了誓言ζ 2024-08-18 02:49:07

由于 MATLAB 与 Java 无缝集成,因此您可以使用 Jython 编写脚本并从 MATLAB 调用该脚本(您可能需要添加一个薄的纯 JKava 包装器才能实际调用 Jython 代码)。我从未尝试过,但我不明白为什么它不起作用。

Since MATLAB seamlessly integrates with Java, you can use Jython to write your script and call that from MATLAB (you may have to add a thin pure JKava wrapper to actually call the Jython code). I never tried it, but I can't see why it won't work.

臻嫒无言 2024-08-18 02:49:07

就像 Daniel 所说,您可以使用 py.txt 文件直接从 Matlab 运行 python 命令。命令。要运行任何库,您只需确保 Malab 正在运行安装库的 python 环境:

在 Mac 上:

  • 打开一个新的终端窗口;

  • 类型:which python(找出Python默认版本的安装位置);

  • 重新启动Matlab;

  • 在命令行中输入: pyversion('/anaconda2/bin/python') (显然替换为您的路径)。
  • 您现在可以运行默认 python 安装中的所有库。

例如:

<块引用>

py.sys.版本;

py.sklearn.cluster.dbscan

Like Daniel said you can run python commands directly from Matlab using the py. command. To run any of the libraries you just have to make sure Malab is running the python environment where you installed the libraries:

On a Mac:

  • Open a new terminal window;

  • type: which python (to find out where the default version of python is installed);

  • Restart Matlab;

  • type: pyversion('/anaconda2/bin/python'), in the command line (obviously replace with your path).
  • You can now run all the libraries in your default python installation.

For example:

py.sys.version;

py.sklearn.cluster.dbscan

幼儿园老大 2024-08-18 02:49:07

这似乎是将函数从 Python“隧道”到 MATLAB

http://code.google.com/p/python-matlab-wormholes/

最大的优点是你可以用它处理 ndarrays,这是标准不可能的程序的输出,如之前所建议的。 (如果您认为这是错误的,请纠正我 - 这会帮我省去很多麻烦:-))

This seems to be a suitable method to "tunnel" functions from Python to MATLAB:

http://code.google.com/p/python-matlab-wormholes/

The big advantage is that you can handle ndarrays with it, which is not possible by the standard output of programs, as suggested before. (Please correct me, if you think this is wrong - it would save me a lot of trouble :-) )

夜巴黎 2024-08-18 02:49:07

由于 Python 是一种更好的粘合语言,因此调用 < a href="http://en.wikipedia.org/wiki/MATLAB" rel="nofollow noreferrer">MATLAB 是来自 Python 的程序的一部分,而不是反之亦然。

查看Mlabwrap

Since Python is a better glue language, it may be easier to call the MATLAB part of your program from Python instead of vice-versa.

Check out Mlabwrap.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文