1

Python は初めてで、matlab 変数を Python に渡したいと考えています。次のコードは、Python スクリプトと引数を取ります。例: python('square.py', '5'). この matlab スクリプトを介して Python に変数を渡すことは可能でしょうか? 例えば:

python('square.py', 'value')
function [result status] = python(varargin)

cmdString = '';

% Add input to arguments to operating system command to be executed.
% (If an argument refers to a file on the MATLAB path, use full file path.)
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
        % This is a valid file on the MATLAB path
        if isempty(dir(thisArg))
            % Not complete file specification
            % - file is not in current directory
            % - OR filename specified without extension
            % ==> get full file path
            thisArg = which(thisArg);
        end
    else
        % First input argument is PythonFile - it must be a valid file
        error('MATLAB:python:FileNotFound', 'Unable to find Python file: %s', thisArg);
    end
end

  % Wrap thisArg in double quotes if it contains spaces
  if any(thisArg == ' ')
    thisArg = ['"', thisArg, '"'];
  end

  % Add argument to command string
  cmdString = [cmdString, ' ', thisArg];
end

% Execute Python script
errTxtNoPython = 'Unable to find Python executable.';

if isempty(cmdString)
  error('MATLAB:python:NoPythonCommand', 'No python command specified');
   elseif ispc
  % PC
  pythonCmd = '/usr/bin/python';
  cmdString = ['python', cmdString];
  pythonCmd = ['set PATH=',pythonCmd, ';%PATH%&' cmdString];
  [status, result] = dos(pythonCmd);
else
  % UNIX
  [status ignore] = unix('which python'); %#ok
  if (status == 0)
    cmdString = ['python', cmdString];
    [status, result] = unix(cmdString);
  else
    error('MATLAB:python:NoExecutable', errTxtNoPython);
  end
end

% Check for errors in shell command
if nargout < 2 && status~=0
  error('MATLAB:python:ExecutionError', ...
    'System error: %sCommand executed: %s', result, cmdString);
end
4

1 に答える 1

2

少量の数値の場合、コードに基づいて、何かに基づいて何かを記述しprintf、基本的にフォーマットされた数値の文字列を python ルーチンに渡すことができます。Python ルーチンは、それを解析して数値に戻す必要があります。

より大きなデータのジャンクについては、それを一時ファイル (csv として、または .xml を使用したバイナリとしてfwrite) に書き込んで、ファイル名を渡すことができます。Linux を実行していて、たとえば /tmp を tmpfs (RAM ディスクのような) としてマウントしている場合、それを一時ストレージとして使用するとプロセスが高速化されます。

Python と Matlab の間で UNIX パイプを使用する人もいます。例としてhttp://danapeerlab.googlecode.com/svn/trunk/freecell/depends/common/python/matlabpipe.py

于 2012-12-04T16:04:08.903 に答える