How to invoke a matlab function from mathematica?

假装没事ソ 提交于 2019-12-03 15:31:54
Szabolcs

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)

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

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.

Szabolcs

There is now a new package for this --- MATLink. It is the most complete such package I am aware of. (Disclaimer: I'm one of the developers of MATLink.)

MATLink lets you ...

  • seamlessly call MATLAB functions form Mathematica

  • transfer data between the two systems

Most MATLAB data types are supported, including sparse arrays, structs and cells.

A more complete description is available here. For detailed examples, see the website.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!