Passing numpy arrays to matlab

David Cournapeau david at ar.media.kyoto-u.ac.jp
Mon Nov 6 20:23:29 CST 2006


Hi,

    I am trying to find a nice way to communicate between matlab and 
python. I am aware of pymat, which does that, but the code is 
deprecated, and I thing basing the code on ctypes would lead to much 
more robust code.

    http://claymore.engineer.gvsu.edu/%7Esteriana/Software/pymat.html

I have a really simple prototype which can send and get back data from 
matlab, but I was wondering if it would be possible to use a scheme 
similar to ctypes instead of having to convert it by hand. Let me 
present the way communication with matlab is done:

    - open a matlab session, which on unix launch a matlab process, and 
set up pipes between the calling process and matlab process for 
communication
    - To send data from the calling process to matlab, you first have to 
create a mxArray, which is the basic matlab handler of a matlab array, 
and populating it. Using mxArray is very ackward : you cannot create 
mxArray from existing data, you have to copy data to them, etc... (it is 
one of the reason I started looking in python in the first place: 
interfacing matlab with foreign code is really not a nice experience, 
and the API is not rich enough to do many interesting things; I am 
actually amazed how poor this part of matlab is, a product which is now 
20 years old).

    I was wondering if there was a way to extend a numpy array so that I 
could send directly numpy arrays to matlab C functions expecting a , 
with ctypes doing the hard work. For example, now, to send data to 
matlab, I do:

    session   = MatlabEngine()
    # data is a numpy array, 'dataname' a string with its name inside 
matlab interpreter
    session.put(data, 'dataname')

The put function has do to a lot for work:
    - first, getting metadata from data (dimensions, real or complex, 
etc...)
    - then creating a mxArray with the same metadata
    - then populating the mxarray by copying the data from the numpy array.

And of course, taking care that all mxarrays are detroyed, otherwise, 
memory leak... That's why I was thinking about something a bit smarter: 
creating a mxarray class which implements the numpy interface. I could 
create a mxarray from a numpy array easily, send a mxarray directly to C 
function with ctypes, etc... Is this doable ? Would this take care of 
correct destruction of mxarrays ? I really don't know much about the 
internals of numpy arrays, so I don't really know how to start,

    cheers,

    David

-------------------------------------------------------------------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642




More information about the Numpy-discussion mailing list