75

MATLAB から Python 関数を呼び出す必要があります。これどうやってするの?

4

13 に答える 13

47

私のシステムには同様の要件があり、これが私の解決策でした:

MATLAB には perl.m という関数があり、MATLAB から perl スクリプトを呼び出すことができます。使用しているバージョンに応じて、次のような場所にあります

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

python.m という名前のコピーを作成し、perl を python ですばやく検索して置換し、設定されたコマンド パスを再確認して、python のインストールをポイントします。これで、MATLAB から Python スクリプトを実行できるようになります。

「sqd.py」として保存されたPythonの単純な二乗関数。当然、これを適切に行っていれば、入力引数、有効な数値などのテストでいくつかのチェックが必要です.

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
>>
于 2009-11-10T17:22:51.933 に答える
30

Matlab 2014b では、Python ライブラリを matlab から直接呼び出すことができます。py.すべてのパケット名にプレフィックスが追加されます。

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

wrapped = 

  Python list with no properties.

    ['example']
于 2015-03-21T23:17:51.013 に答える
20

他の人が示唆しているように、MATLABからPythonを実際に呼び出すには、このMEXファイルを試してください。それはかなりまともな統合を提供します: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);
于 2012-05-29T10:16:14.443 に答える
14

Python スクリプトを C プログラムに埋め込んでから、MATLAB を使用して C プログラムをMEX することもできますが、結果をファイルにダンプする場合と比較して、かなりの作業になる可能性があります。

PyMatを使用して Python で MATLAB 関数を呼び出すことができます。それとは別に、SciPyにはいくつかの MATLAB 重複関数があります。

ただし、MATLAB から Python スクリプトを実行する必要がある場合は、システムコマンドを実行してスクリプトを実行し、結果をファイルに保存して、後で MATLAB で読み取ることができます。

于 2009-11-10T13:09:31.547 に答える
11

@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.

于 2012-08-03T22:37:44.643 に答える
10

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.

于 2012-03-19T04:09:25.117 に答える
7

Matlab 2014b 以降、Python 関数を直接呼び出すことができます。次のように、接頭辞 py、次にモジュール名、最後に関数名を使用します。

result = py.module_name.function_name(parameter1);

Python スクリプトとは異なる作業ディレクトリにいる場合は、Matlab から呼び出すときにスクリプトを Python 検索パスに追加してください。

詳細はこちらをご覧ください。

于 2016-10-12T18:43:29.867 に答える
4

MATLABの関数に関するほとんど知られていない (そしてほとんど文書化されていない) 事実: unixoid システムでは、環境変数またはMATLAB の起動時に指定されたインタープリターを使用します。したがって、MATLAB を次のように起動するとsystem()SHELLMATLAB_SHELL

SHELL='/usr/bin/python' matlab

以降のsystem()呼び出しでは、デフォルトのシェルの代わりにPythonがインタープリターとして使用されます。

于 2013-01-03T09:08:06.480 に答える
4

私はに適応させ、perl.mpython.mの人の参考のためにこれを添付しましたが、Pythonスクリプトからの出力をMATLAB変数に返すことができないようです:(

これが私の M ファイルです。C:\python27_64私のコードでは、Python フォルダー を直接指していますが、これはシステムによって変更されることに注意してください。

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

編集 :

PATHを更新してから Perl を呼び出すことにより、元の perl.mが MATLAB フォルダー内のPerlインストールを指しているという問題を解決しました。上記の関数は、私の Python インストールを指しています。ファイルを呼び出したとき、それは別のディレクトリにあり、そのディレクトリ内の他のファイルを呼び出しました。これらはPATHに反映されていないため、Python ファイルを Python ディストリビューションに easy_install する必要がありました。function.py

于 2012-02-24T14:23:16.427 に答える
3

MATLABは Java とシームレスに統合されているため、Jython を使用しスクリプトを記述し、それを MATLAB から呼び出すことができます (実際に Jython コードを呼び出すには、薄い純粋な JKava ラッパーを追加する必要がある場合があります)。試したことはありませんが、なぜうまくいかないのかわかりません。

于 2011-02-21T12:02:51.070 に答える
-1

Pythonはより優れたグルー言語であるため、プログラムの MATLAB 部分を Python から呼び出す方が、その逆よりも簡単な場合があります

Mlabwrapをチェックしてください。

于 2010-04-16T01:48:54.060 に答える