53

How can I call MATLAB functions directly from Mathematica and transfer data/variables between the two systems?

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
siva82kb
  • 631
  • 6
  • 4
  • 2
    I don't think you can use NETLink on a Mac... – rm -rf Sep 04 '12 at 22:13
  • 4
    @siva82kb: It might even be possible to use NETLink on a Mac using something like mono. I think I've heard someone do this on linux. On the other hand that won't help as the Mac version of matlab presumably doesn't provide a COM interface, which I think is what you are actually accessing. I think you should first get the information which possibilities there are to interact with matlab from another program on a Mac, presumably the matlab support or community can answer that. With that information, we could probably help you to decide which of those would be easiest to use from Mathematica... – Albert Retey Sep 05 '12 at 09:20
  • 7
    which Matlab functions do you need to call? And why? Maybe you could achieve the same with Mathematica? I agree that sometimes algorithms are missing in Mathematica (like in NonlinearModelFit) and then you have to use Matlab (lsqcurvefit), but that should be rare. – Rolf Mertig Sep 05 '12 at 09:58
  • Related SO questions: (1), (2), (3). – Alexey Popkov Jan 24 '13 at 05:36
  • @phantomas1234 Wish I had seen that earlier ... – Szabolcs Jan 24 '13 at 17:45
  • @AlexeyPopkov We could make this a general multiplatform question. Could you re-post your NETLink answer here? – Szabolcs Jan 25 '13 at 03:23
  • @Szabolcs My NETLink answer was very basic. The OP says he used NETLink for calling Matlab himself and I think he is much more experienced in this field than I am. But the question seems to be actual and there is still no complete answer. So I'll repost my answer in Community Wiki mode. – Alexey Popkov Jan 25 '13 at 13:37
  • 3
    Note: This question is being repurposed to be a general repository of information on calling MATLAB from Mma on any platform (including OS X). Please see my answer for a Mac specific solution. – Szabolcs Jan 26 '13 at 03:16

4 Answers4

65

2014-04-12 NOTICE: MATLAB R2014a contains a bug that breaks MATLink on OS X and Linux (Windows is fine). If you use MATLink on OS X or Linux, please consider keeping MATLAB R2013b until R2014b comes out. Due to the nature of the problem there is no quick workaround that we could apply in MATLink.

For full compatibility with Mathematica 10, please upgrade to MATLink 1.1.


Note: If you're using this package, please let us know how! Understanding how people use it helps us improve it in the right areas.


There is a new cross platform package for this, called MATLink. It allows calling MATLAB functions seamlessly, directly from Mathematica, as well as transferring data between the two systems. See below for a small tutorial:

[]9
(source: matlink.org)

Disclosure: I am one of the developers of MATLink.


Installation

Go to the MATLink home page and follow the instructions there. The simplest way is to download the archive and extract it to this directory:

SystemOpen@FileNameJoin[{$UserBaseDirectory, "Applications"}]

Then make sure you follow the operating system specific instructions described under "Link with MATLAB" on the home page.

Using MATLink

Load MATLink by evaluating

Needs["MATLink`"]

and launch MATLAB using

OpenMATLAB[]

This will launch a new MATLAB process in the background that Mathematica can communicate with.

To evaluate arbitrary MATLAB commands, use MEvaluate. The output will be returned as a string.

MEvaluate["magic(4)"]

(* ==>
ans =

    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1
 *)

To transfer data to MATLAB, use MSet:

MSet["x", Range[10]]
MEvaluate["x"]
(* ==>
x =

     1     2     3     4     5     6     7     8     9    10
*)

To transfer data back, use MGet:

MGet["x"]

(* ==> {1., 2., 3., 4., 5., 6., 7., 8., 9., 10.} *)

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

MATLAB functions can be wrapped using MFunction and called directly from Mathematica:

eig = MFunction["eig"]
eig[{{1, 2}, {3, 1}}]

(* ==> {{3.44949}, {-1.44949}} *)

See the docs for more advanced usage and other functionality.

Simple examples

Plot the membrane from MATLAB's logo in Mathematica and manipulate the vibration modes:

Manipulate[
 ListPlot3D@MFunction["membrane"][k],
 {k, 1, 12, 1}
]

A bucky ball straight from MATLAB:

AdjacencyGraph@Round@MFunction["bucky"][]

enter image description here

Show Mathematica data in a zoomable MATLAB figure window:

mlf = LibraryFunctionLoad["demo_numerical", "mandelbrot", {Complex}, Integer];
mandel = Table[mlf[x + I y], {y, -1.25, 1.25, .002}, {x, -2., 0.5, .002}];
MFunction["image", "Output" -> False][mandel]

See the webpage for a few more complex examples.


Bugs and problems: If you find any, please do report them in email (matlink.m at gmail), on GitHub, or by commenting on this post. A support chatroom is also available.

Glorfindel
  • 547
  • 1
  • 8
  • 14
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
  • That's so cool!! – user0501 May 02 '13 at 01:15
  • 1
    It actually works! – bill s May 02 '13 at 04:54
  • 3
    I am using MATLink to drive the Data Acquisition Toolbox on a test system I am developing. I would rather work entirely in Mathematica, but a) I don't believe there is a straightforward way to operate data acquisition systems from Mathematica and b) this approach lets me recycle another engineer's MATLAB code and get up to speed faster. Thanks for the package. – Daniel W Nov 24 '13 at 13:35
  • I use MATLink to diagonalize large matrices (>10^4*10^4) and then process the result in MMA. Sometimes I also use the Spectrogram from Matlab. Thanks for making it so easy to use. – Leo Fang Sep 10 '14 at 03:16
  • One thing I wonder (not that I need it, just curious) is that do you plan to add the ability of handling arbitrary precision arithmetic to MATLink in the near future? – Leo Fang Sep 10 '14 at 03:18
  • @LeoFang Unfortunately I have very little time recently, and I couldn't even get much more important stuff get done. So realistically this is unlikely in the near future (meaning next 1 yr). But can you elaborate on it more? Do you mean the multiprecision toolbox? Also: user feedback is important in how we prioritize stuff, so thanks for commenting! – Szabolcs Sep 10 '14 at 14:36
  • @Szabolcs, what I had in mind is that we know in MMA we can handle arbitrary precision (say 30 digit precision) by setting a=N[a, 30]. However if one sends this 30-digit object a to Matlab through MATLink, it is converted to a double precision number and some precision is therefore lost. I'm not an expert in Matlab, so I google it and found a Symbolic Math Toolbox that seems able to handle it. But there exists other toolbox too and I have no idea how's the performance... – Leo Fang Sep 10 '14 at 14:43
  • @Szabolcs Thanks for this wonderful works-out-of-the-box experience. All I had to do was SetEnvironment[ "PATH" -> StringJoin[Last@GetEnvironment[{"PATH"}], ";C:\\Program Files\\MATLAB\\MATLAB Production Server\\R2015a\\bin\ \\win64"]]. I guess Matlab (no longer?) adds that to the path by default or I didn't let it. – masterxilo Oct 03 '16 at 20:23
  • @masterxilo I think it never did add it to the path. It adds bin but not \bin\win64. In principle it should be possible for us to detect this path (through registry settings) and add it automatically. Maybe in the next version if we ever get the time ... there's a huge todo list, but it would take a couple of weeks of full time work which I simply don't have time for. – Szabolcs Oct 03 '16 at 20:33
15

Here I show the basic way to call MATLAB using NETLink under Windows via the MATLAB COM interface. This answer is Community Wiki, feel free to extend it to others platforms and/or improve it!

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

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

Now one 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

"
Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
Alexey Popkov
  • 61,809
  • 7
  • 149
  • 368
11

I'll leave this up on GitHub, but I won't maintain the port. I recommend using MATLink instead.


There's a package on the Wolfram Library Archive called mEngine that allows calling MATLAB from Mathematica. What it can do is:

  • execute arbitrary MATLAB commands and retrieve their output as a string
  • transfer array variables between Mathematica and MATLAB

It is mirroring the functionality of the "MATLAB Engine", MATLAB's C/Fortran interface.

This functionality can be used to set up Mathematica wrappers for MATLAB functions by transferring the arguments and return values through global variables. Ugly, yes, but it works and it's useful.


The original version of mEngine was written for Windows and comes with a precompiled executable that works on 32 bit systems. For other operating systems it need to be recompiled with modifications.


Using mEngine on OS X

Several modifications need to be made to mEngine before it can be compiled on OS X and it'll work on 64 bit systems. I put such a modified version on GitHub. Please get it from there and do not mix the files from this modified version with the original version found on the Wolfram Library Archive.

I uploaded a precompiled binary here. It should work on 64 bit OS X 10.6 or later. Important: When using this, the mEngine.sh file needs to be edited and the MATLAB variable set to the location of your MATLAB installation.


Note: If you get an error about not being able to start MATLAB, please first check that the PATH variable in mEngine.sh is set to point to MATLAB's bin directory (which is inside the .app bundle). If it still doesn't work, please try to change the engOpen(NULL) call in open.c to engOpen("/path/to/matlab") (of course substituting the correct path for your system; it should look similar to /Applications/MATLAB.app/bin/matlab, but it'll depend on where you installed MATLAB and what you named it).

If it still doesn't work for you or if you find crashes, please leave a comment.

Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
2

For what it's worth, there also seems to be a way to integrate Mathematica into matlab (the other way around) using the

"Mathematica Symbolic Toolbox for MATLAB--Version 2.0"

http://ch.mathworks.com/matlabcentral/fileexchange/6044-mathematica-symbolic-toolbox-for-matlab-version-2-0

I have not personally tested this though, it seems quite old (2004, 2010).

masterxilo
  • 5,739
  • 17
  • 39