Thursday, August 24, 2006

Matlab and Perl: returning matrixes and cells from Perl to Matlab

Matlab, as one of the most preferable hight level languages among the scientist all over the world, provides interfaces to other programming languages. Normally you can attach to Matlab scripts programs written in: ANSI C, Java SDK , Fortran. This process is called external interfaces and information about it can be found here.

In addition to those languages, there is also possibility to use Perl programs within Matlab scripts. This can attributed to the fact, that Matlab, by default, has embedded Perl interpreter (in fact, it's tripped-down version of the interpreter). Therefor, you can use Perl scripts without any problems.

However, in contrast to ANSI C, Java SDK , Fortran interfaces, Matlab doesn't have any build in routines, to pass and return matrices, cells, vectors to and from Perl. The only thing returned to Matlab is string, which represents stdout of Perl script, meaning, that Matlab receives everything what is returned by print functions in Perl. Everything which normally is printed on stdout, is assigned to one string variable in Matlab. For instance if myscriptInPerl.pl is simple perl script print to console something, then executing this in Matlab console:

A = perl('myscriptInPerl.pl', var1,' var2', var3);

assigns to variable A, all output of myscriptInPerl.pl.

Based on that, my own solution to get matrices, cells, vectors, etc. returned from Perl, is to return string, representing Matlab's code, and executing function eval(A) in Matlab. For example

#myperlscript.pl
#Example file, with Perl scribt to be executed by Patlab
#

$out = "myVector = [2 3 4 5 5 6]; "
#variable with string representing Matlab vector

print $out; #print $out to Matlab

Executing above script in Matlab and evaluating returned string will create myVector variable in Matlab:

A = perl('myscriptInPerl.pl', var1,' var2', var3);
eval(A);

myVector =

2 3 4 5 5 6