Tuesday, March 8, 2016

Running Matlab from inside Python

I have been programming in Python since I was working for Intel. I am amazed on how friendly is its syntax and how few lines of code can do many things. Later, it was exciting to know that Mathworks (the company that develops Matlab) decided to make its powerful software to be natively compatible with Python. Now it is possible to combine the easy Python syntax with the mathematical power inside Matlab and exchange data between the two (or at least it has become very easy).

This Matlab Engine for Python is available from Matlab 2014b. To install it just open a command shell (it MUST be run as administrator to work properly), and type:

    cd %MATLAB_PATH%\%MATLAB_VERSION%\extern\engines\python
    %PYTHON_PATH%\python.exe setup.py install

The %MATLAB_PATH% variable points to the directory where we have installed Matlab. %MATLAB_VERSION% is, as it says, the Matlab version to use. And %PYTHON_PATH% is the directory where have Python installed. In my case, these variables have the values:

    %MATLAB_PATH% = C:\Program Files\MATLAB
    %MATLAB_VERSION% = R2016a
    %PYTHON_PATH% = C:\Python27

Actually, without defining variables, in my machine it looks like this:



If the "error" word appears after executing these commands, check out to see what is missing. Most of the times the error log has enough information to know the next step for fixing the issue.

Once the engine has been installed, it is ready to go. Let's now run an example to plot a sine wave in Matlab, from Python. Open a Python shell and write...

    import matlab
    eng = matlab.engine.start_matlab()
    x = eng.linspace(0.0,5.0,1000.0)
    y = eng.sin(x)
    eng.figure(nargout=0)
    eng.hold("on",nargout=0)
    eng.box("on",nargout=0)
    eng.line(x, y, nargout=0)

When finished, you should see a Matlab graph pop out. With this, we have enabled the Matlab Engine for Python.



I highly recommend you to check these examples in Matlab's website:

- Install MATLAB Engine API for Python
Install MATLAB Engine API for Python in Nondefault Locations
Start and Stop MATLAB Engine for Python
Connect Python to Running MATLAB Session
Call MATLAB Functions from Python
Call MATLAB Functions Asynchronously from Python
Call User Script and Function from Python
Redirect Standard Output and Error to Python
Use MATLAB Engine Workspace in Python
Use MATLAB Handle Objects in Python
Use MATLAB Arrays in Python
Sort and Plot MATLAB Data from Python
Get Help for MATLAB Functions from Python

And now, let's have fun with a whole world of possibilities!

No comments:

Post a Comment