Calling a matlab function with python subprocess.Popen

7 ビュー (過去 30 日間)
Shini Bhatt
Shini Bhatt 2016 年 10 月 22 日
コメント済み: Shini Bhatt 2016 年 11 月 2 日
Hi,
I have a python code which runs a matlab function sussum(a,nx,ny) in the background with subprocess.Popen. I am not able to get it working. Because I'm unable to pass the input arguments to matlab correctly. Here is the python code:
#!/usr/bin/env python
import matlab.engine
import scipy.io as sio
import numpy as np
import subprocess as sb
nproc = 5
input = sio.loadmat('sus_py.mat')
totq = input['totq']
nx,ny = input['nx'],input['ny']
nq = totq+1
nx,ny = matlab.int32(nx.tolist()) , matlab.int32(ny.tolist())
iq = range(1,nq)
gp = len(iq)/nproc
list = [iq[j:j+nproc] for j in range(0,len(iq),nproc)]
for g in range(0,len(list)):
i = len(list[g])
p = []
for n in range(0,i):
a = matlab.int32(list[g][n])
fun = '-r "sussum(a,nx,ny); exit" '
lmb = ['/usr/local/bin/matlab','-nodesktop','-nosplash','-nodisplay','-nojvm',fun]
p.append(sb.Popen(lmb))
for q in p:
q.wait()
The python script executes in the command terminal of a cluster network, until it spits out the error message: Undefined function or variable 'a'.
I am sure that the matlab function sussum(a,nx,ny) works fine because I have tested it using Python-Matlab API as matlab.engine.start_matlab().sussum(a,nx,ny) and it gave the desired outputs. Any help in getting the python code running with subprocess.Popen() will be highly appreciated.

採用された回答

Walter Roberson
Walter Roberson 2016 年 10 月 22 日
You need to convert the values of the variable to text and insert them at the appropriate place.
Or, you need to push the variables to the MATLAB engine and send the MATLAB engine a command. The method you are using now appears to use both the engine and a new MATLAB process.
  3 件のコメント
Walter Roberson
Walter Roberson 2016 年 10 月 22 日
fun = '-r "sussum(%g,%g,%g); exit" ' % (a,nx,ny)
Shini Bhatt
Shini Bhatt 2016 年 11 月 2 日
Thanks! The edit you suggested works as long as nx,ny are 1-D or 2-D array. N-D array with N>2 has different structures in Matlab and Python, so matlab doesn't accept such inputs.
I found another answer that modifies python N-D arrays to be acceptable to matlab. Although, I haven't used this yet: https://www.mathworks.com/matlabcentral/answers/157347-convert-python-numpy-array-to-double

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeCall MATLAB from Python についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by