Running Matlab as a Python subprocess

share on google plus share on facebook share on twitter share on linkedin share via email

Although NumPy and Scipy usually provide all the tools you need (and more) for scientific computing, sometimes you may want to use a bit of Matlab in the background. In my case, for example, to use rref. Conveniently, Matlab can be run as a Python subprocess, provided of course that Matlab is installed on your system.

01.import os
02. 
03.from subprocess import Popen
04.from scipy.io import loadmat
05.from scipy.io import savemat
06. 
07.import numpy as np
08. 
09.infile = os.path.join(os.path.dirname(__file__), 'infile.mat')
10.outfile = os.path.join(os.path.dirname(__file__), 'outfile.mat')
11. 
12.with open(infile, 'wb+') as fp: pass
13.with open(outfile, 'wb+') as fp: pass
14. 
15.A = np.array([
16.[1, 0, 0, 0],
17.[0, 1, 0, 0],
18.[0, 0, 1, 0],
19.[0, 0, 0, 1]], dtype=float)
20. 
21.indict = {'A': A}
22. 
23.savemat(infile, indict)
24. 
25.matlab  = ['matlab']
26.options = ['-nosplash', '-r']
27.command = ["load('{0}');[R, jb]=rref(A);save('{1}');exit;".format(infile, outfile)]
28. 
29.# on mac use the full path to matlab or add the path to your .profile
30.# matlab = ['/Applications/MATLAB_R2016a.app/bin/matlab']
31. 
32.# on windows use:
33.# options = ['-nosplash', '-wait', '-r']
34. 
35.p = Popen(matlab + options + command)
36. 
37.stdout, stderr = p.communicate()
38. 
39.outdict = loadmat(outfile)
40.jb = outdict['jb'].tolist()[0]
41. 
42.print jb
43. 
44.# should be [1, 2, 3, 4]
45.# don't forget Matlab is 1-based
46.# so convert to [0, 1, 2, 3]

Leave a response

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>