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.

import os

from subprocess import Popen
from import loadmat
from import savemat

import numpy as np

infile = os.path.join(os.path.dirname(__file__), 'infile.mat')
outfile = os.path.join(os.path.dirname(__file__), 'outfile.mat')

with open(infile, 'wb+') as fp: pass
with open(outfile, 'wb+') as fp: pass

A = np.array([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]], dtype=float)

indict = {'A': A}

savemat(infile, indict)

matlab  = ['matlab']
options = ['-nosplash', '-r']
command = ["load('{0}');[R, jb]=rref(A);save('{1}');exit;".format(infile, outfile)]

# on mac use the full path to matlab or add the path to your .profile
# matlab = ['/Applications/']

# on windows use:
# options = ['-nosplash', '-wait', '-r']

p = Popen(matlab + options + command)

stdout, stderr = p.communicate()

outdict = loadmat(outfile)
jb = outdict['jb'].tolist()[0]

print jb

# should be [1, 2, 3, 4]
# don't forget Matlab is 1-based
# 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>