Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke a matlab function from mathematica?

I would like to call a matlab function from mathematica. How best to do that?

I have found an ancient post on Wolfram site describing a way to do this, is this still the way to connect the two?

like image 852
John Avatar asked Dec 22 '10 15:12

John


3 Answers

You can try NETLink for this at least under Windows:

In[1]:= Needs["NETLink`"]
matlab = CreateCOMObject["matlab.application"]

Out[2]= «NETObject[COMInterface[MLApp.DIMLApp]]»

And then you can invoke Matlab functions:

In[4]:= matlab@Execute["version"]

Out[4]= "
ans =

7.9.0.529 (R2009b)

"

In[5]:= matlab@Execute["a=2"]

matlab@Execute["a*2"]

Out[5]= "
a =

     2

"

Out[6]= "
ans =

     4

"

HTH

like image 139
Alexey Popkov Avatar answered Nov 20 '22 16:11

Alexey Popkov


You can use mEngine. The precompiled Windows MathLink executable works with Mathematica 8. On Windows you may need to add MATLAB to the system path.

The advantage of this compared to the NETLink method is that transferring variables between Mathematica and MATLAB will be as easy as mGet["x"] or mPut["x"]. Although this might be possible with NETLink too, the advantage of mEngine is that you don't need to implement it yourself (which is great if like me you don't know anything about COM or .NET)

like image 24
Szabolcs Avatar answered Nov 20 '22 16:11

Szabolcs


I would imagine that this is a difficult problem in general, but can be easily solved with a little programming for a particular case. I'll demonstrate with C#.

I would build a string of calls, like so.

  • Mathematica calls a C# program, through MathLink. This is near trivial to setup, and Mathematica has a sample project in Mathematica\8.0\SystemFiles\Links\NETLink directory.
  • C# program calls Matlab. There are several ways to make this call, and this handy link describes how to do it and offers sample code.
  • C# program returns Matlab results.

All in all I could do this in less than 50 lines of C# code, for a specific problem. Not too much work, in other words. Possible problems are data conversion, but if you want to send back and forth arrays of data, MathLink offers a lot out of the box. Similarly Mathematica can be linked to MATLAB through Java, though I haven't done that myself.

Perhaps the easiest connection could be made through Python. Mathematica offers an installable MathLink python library, located at Mathematica\8.0\SystemFiles\Links\NETLink, and Matlab has an addon library called PyMat, which can be downloaded here, but this package hasn't been maintained for a long time and supports only the most ancient of Matlabs.

Alternatively you can forgo Matlab altogether in favor of SAGE and/or numpy.

like image 33
Gleno Avatar answered Nov 20 '22 14:11

Gleno