Tuesday, March 2, 2010

[pymex] Python in Matlab

So I've been pretty busy on a few different things. One of those things happens to be pymex. I often need to extend Matlab to do something

To extend Matlab's capabilities it's necessary to write mex files in C/C++. Python is quick to code and it already has a bunch of available modules. With pymex a programmer can embed Python code inside of Matlab and avoid the whole mex file thing.

As an added benifit I also wrote a python module called 'matlab'. This module does two things. First, it provides a simple print function which prints to Matlab's command window (like mexPrintf). Second, it allows Python variables to be 'pushed' to Matlab.

matlab.mex_print(str, ...)
'''Like Pythons built-in print function, takes a variable
length of objects, converts them to strings using str(),
and prints the result to the Matlab command window.'''

matlab.push(varname, var, ...)
'''Using the Matlab function 'assignin', creates a Matlab
variable in the caller's scope from 'var' named 'varname'.
The 'varname' must be a valid Matlab variable name.
The 'var' must be a scalar; lists, tuples, and objects are
not supported yet.'''


Here's a sample script to show what pymex can do.

pyscript = sprintf([...
'import matlab\n', ...
'x = 7\n', ...
'for i in range(x):\n', ...
' matlab.mex_print(i)\n', ...
' matlab.push("i_%%d" %% i, i)\n', ...
'matlab.mex_print("demo complete!")\n', ...
]);

pymex(pyscript);

No comments:

Post a Comment