Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I interact with MATLAB from Python?

Tags:

A friend asked me about creating a small web interface that accepts some inputs, sends them to MATLAB for number crunching and outputs the results. I'm a Python/Django developer by trade, so I can handle the web interface, but I am clueless when it comes to MATLAB. Specifically:

  • I'd really like to avoid hosting this on a Windows server. Any issues getting MATLAB running in Linux with scripts created on Windows?
  • Should I be looking into shelling out commands or compiling it to C and using ctypes to interact with it?
  • If compiling is the way to go, is there anything I should know about getting it compiled and working in Python? (It's been a long time since I've compiled or worked with C)

Any suggestions, tips, or tricks on how to pull this off?

like image 487
Pete Avatar asked Feb 13 '10 00:02

Pete


People also ask

How do I add MATLAB to Python?

Install Using pip Starting with MATLAB R2022b, you can use the pip command to install the API. Choose one of the following procedures and execute from the system prompt. To install from the MATLAB folder, on Windows® type: cd "matlabroot\extern\engines\python" python -m pip install .


2 Answers

There is a python-matlab bridge which is unique in the sense that Matlab runs in the background as a server so you don't have the startup cost each time you call a Matlab function.

it's as easy as downloading and the following code:

from pymatbridge import Matlab mlab = Matlab(matlab='/Applications/MATLAB_R2011a.app/bin/matlab') mlab.start() res = mlab.run('path/to/yourfunc.m', {'arg1': 3, 'arg2': 5}) print res['result'] 

where the contents of yourfunc.m would be something like this:

%% MATLAB function lol = yourfunc(args)     arg1 = args.arg1;     arg2 = args.arg2;     lol = arg1 + arg2; end 
like image 108
Max Jaderberg Avatar answered Sep 19 '22 14:09

Max Jaderberg


Take a look at mlabwrap which allows you to call Matlab via a python API

like image 42
Jon Avatar answered Sep 21 '22 14:09

Jon