MATLink is a Mathematica^{™} application to communicate with MATLAB^{™}, providing functionality to easily transfer data between the two systems, and use MATLAB functions, scripts and toolboxes from within Mathematica. MATLink is not a substitute for MATLAB, nor is it a replacement for actual knowledge of MATLAB and Mathematica; it is merely an application that allows the user to harness the power of both computational systems to program and develop more efficiently.
MATLink is written in Mathematica and C++ and connects to MATLAB using the MATLAB Engine interface. The image to the right is an overview of the different functions in MATLink and how they interact with the different systems. This documentation contains
MATLink has four functions that handle various aspects of startup and shutdown of MATLAB and the underlying engine
ConnectEngine
and DisconnectEngine
, which interacts with the MATLAB engine.OpenMATLAB
and CloseMATLAB
, which interacts with MATLAB.OpenMATLAB
, automatically calls ConnectEngine
if the engine is not running, so one can launch MATLAB directly with it after loading the package. Similarly, DisconnectEngine
will automatically terminate any open connection to MATLAB before shutting down the engine.
MATLink uses a session folder in $TemporaryDirectory
to save scripts and functions defined during the current session. These are removed when DisconnectEngine
is called, or by the operating system (typically after a reboot or daily, depending on the system), if there are any abandoned directories after a crash. To manually remove those folders, run MATLink`Developer`CleanupTemporaryDirectories[]
.
ConnectEngine[]
will connect to the MATLAB engine using MathLink.
mengine
binary is not found, ConnectEngine
will try to auto compile it.ConnectEngine
creates a session directory in $TemporaryDirectory
to which MScripts
are written. This directory is automatically removed when DisconnectEngine
is called.DisconnectEngine[]
will terminate the MathLink connection with the MATLAB engine.
DisconnectEngine
will terminate it before shutting down the engine.DisconnectEngine
deletes the session directory in $TemporaryDirectory
that was created by ConnectEngine
.OpenMATLAB[]
will start an instance of MATLAB for use with MATLink.
OpenMATLAB
will call ConnectEngine[]
to launch the engine before starting MATLABCloseMATLAB[]
will close the currently open instance of MATLAB.
Arbitrary MATLAB code can be evaluated in three ways — using MEvaluate
, MATLABCell
or CommandWindow
(only the first two are available on non-Windows operating systems). The primary difference between the three functions is:
MEvaluate
is a Mathematica function that takes MATLAB input as strings, and can be conveniently used in larger programsMATLABCell
is a styled cell in a Mathematica notebook, that is useful for interactive workCommandWindow
is just a Mathematica function that activates a native MATLAB command window interface. With this, one works directly with MATLAB, independent of MATLink (although the variables are still accessible via MATLink).Since there is overhead in transferring instructions and output with MEvaluate
, it is advisable to not display output where not necessary (both, in MATLAB and Mathematica). If you need to run the same set of instructions repeatedly, use an MScript
instead of MEvaluate
.
MEvaluate["code"]
will executecode
in MATLAB as if it were entered at the command prompt and returns the output as text.
MEvaluate
, when successful, will always return a string containing the output from MATLAB's command window.MEvaluate
performance suffers if the output is not suppressed in MATLAB code. If you do not need to see the output of MEvaluate
, use MEvaluate["command;"]
instead of MEvaluate["command"];
.
MEvaluate
is limited to approximatey 100,000 characters. The rest will be truncated.CommandWindow["action"]
will perform"action"
on MATLAB's built-in command window. This function works only on Windows.
CommandWindow["Show"]
displays the command window. When an evaluation is not in progress, this window can be used to input MATLAB commands independently of MATLink.CommandWindow["Hide"]
hides the command window.MATLABCell[]
creates a program cell in the current notebook, whose contents are interpreted as MATLAB code.
Any supported datatype can be transferred from Mathematica to MATLAB and vice versa using MSet
and MGet
respectively. However, one must be aware of the overhead involved in data transfer (when using any link technology) and avoid programming pitfalls that result in unnecessary back-and-forth data transfer (unless absolutely necessary). It is always good practice to transfer as much as possible in one go, and only transfer what is necessary.
Every effort has been made to convert quantities to native data structures in each system (such as arrays in MATLAB and lists in Mathematica) and allow the user to retrun the same data to the originating system without loss of structure, but there are certain exceptions (MATLAB cells). See the translation rules for more information.
MGet["var"]
will return the value of the variablevar
from the MATLAB workspace. Data structures are translated into a Mathematica compatible format.
var
must be a string denoting the name of the variable in MATLABMEvaluate["x = 1:10;"] MGet["x"] (* Out[1]= {1., 2., 3., 4., 5., 6., 7., 8., 9., 10.} *)
MGet
is Listable
MEvaluate["[v, e] = eig(rand(5));"] {v, e} = MGet[{"v", "e"}]
MEvaluate["s = size(zeros(3,4));"] s = MGet["s"] (* Out: {3., 4.} *)
MGet
on objects (classdef
objects) or data structures which contain objects. This will crash MATLAB because of a MATLAB bug. See the known issues section for additional details.MSet["var", value]
will assign value to variablevar
in the MATLAB workspace.
MSet["a", {1,2,3}] MEvaluate["a"] (* Out: a = 1 2 3 *)
var
must be a string denoting the name of the variable in MATLABvalue
must be in a MATLink compatible format.MCell
head:MSet["a", MCell[{1, 2, 3}]] MEvaluate["a"] (* Out: a = [1] [2] [3] *)
MCell
is an inert head used withMSet
to indicate that the list be interpreted as a MATLAB cell data structure.
MSet["a", MCell[{1, 2, 3}]] MEvaluate["a"] (* Out: a = [1] [2] [3] *)
MATLAB programming involves script files, which are a series of sequential instructions to the interpreter (executed in the base workspace) or functions, which take zero or more inputs and return zero or more outputs (executed in its own workspace). The MScript
and MFunction
functions allow one to execute MATLAB scripts and functions from within Mathematica. This makes it easy to reuse code found online, either on the MathWorks File Exchange or elsewhere, instead of reimplementing it in Mathematica.
MFunction
offers the functionality to use the multiple output form of MATLAB functions, but the number of outputs must be set explicitly when defining the function.
MScript["scriptname", "commands"]
will create a MATLAB script containingcommands
.
MScript["scriptname", "commands"]
returns MScript["scriptname"]
, which can be evaluated using MEvaluate
.hello = MScript["hello", "disp('Hello world!')"]; MEvaluate@hello (* Out[1] = "Hello world!" *)
MScript
will not overwrite exsiting .m
files. To force overwrite an existing file, use the option "Overwrite" -> True
(default value for "Overwrite"
is False
).MFunction["func"]
represents a MATLAB functionfunc
(that is on MATLAB's path), and can be called directly from within Mathematica.
MFunction["func", "body"]
creates a new.m
file with the contentsbody
and returnsMFunction["func"]
.
eig = MFunction["eig"]; eig[{{1, 2}, {3, 4}}] (* Out[1]= {{-0.372281}, {5.37228}} *)
add = MFunction["add", " function res = add(x,y) res = x+y end "]; add[3, 4] (* Out[1] = 7 *)
add = MFunction["add", "@(x,y)x+y"]; add[3, 4] (* Out[1] = 7 *)Anonymous functions defined in this manner form a closure, as in MATLAB.
MFunction["func", "OutputArguments" -> n]
when func
returns more than one argument (default value for "OutputArguments"
is 1).eigsys = MFunction["eig", "OutputArguments" -> 2]; eigsys[{{1, 2}, {3, 4}}] (* Out[1]= {{{-0.824565, -0.415974}, {0.565767, -0.909377}}, {{-0.372281, 0.}, {0., 5.37228}}} *)
func
returns no outputs (or to suppress output), use MFunction["func", "Output" -> False]
(default value for "Output"
is True
).imagesc = MFunction["imagesc", "Output" -> False]; data = Import["ExampleData/ozonemap.hdf", {"Datasets", "TOTAL_OZONE"}][[20 ;;, All]]; imagesc[data];
Note that MATLAB plots will be opened in a new window, unlike Mathematica plots which are displayed inside the notebook.
MFunction["func", "body"]
, MFunction
will not overwrite exsiting .m
files. To force overwrite an existing file, use the option "Overwrite" -> True
(default value for "Overwrite"
is False
)."body"
is @
, then the function is defined as an anonymous function in MATLAB's workspace and no function file is created.MFunction
assumes a single output argument, which causes errors in some MATLAB functions that return no output.MFunction["disp"]["Hello"] MATLink::errx: Error using disp Too many output arguments. (* Out[1]= $Failed *)Use
"Output" -> False
in such situations.
The following data types can be transferred in both directions:
[1 n]
)[1 1]
)The following can only be transferred from MATLAB to Mathematica:
This section documents the internal rules that govern the translation of data structures from MATLAB to Mathematica and vice versa. You do not need to do this conversion, but you should be aware of how it is converted so that you can design your programs accordingly.
single
and double
are converted to Real
or Complex
(as the case may be)int*
and uint*
are converted to Integer
or Complex
(as the case may be){}
logical
) or true
and false
are converted to True
and False
respectivelychar
is converted to String
struct
is converted to a list of rules{}
Integer
, Real
and Complex
are all converted to double
MCell
headThe OS X (and possibly Linux) versions of MATLAB R2014a contain a bug that breaks MATLink. Unfortunately this bug is in a core MATLAB Engine feature MATLink relies on, and it is not easy to work around it. Until this is resolved, please consider using earlier versions of MATLAB (R2013b or earlier) on OS X or Linux to run MATLink.
At the moment, only arrays with less than 2^31-1
elements are supported. Note that this is true for matrices and multidimensional arrays as well: the total number of matrix elements may not excede 2^31-1
even if the matrix has fewer rows and columns than this. As an example, the largest supported square matrix can be of size 46341 by 46341.
As a reference point, a double precision array with the maximum number of allowed elements would take up 16 GB of memory, so this limit should be more than sufficient for most applications.
Inf and Nan are not supported at the moment. The values returned to Mathematica are not safe to use: operations on them give unpredictable results.
If a MATLAB background process has already been started by MATLink, it will not be possible to launch another instance of MATLAB by clicking on its icon. As a workaround, either start MATLAB before you call OpenMATLAB[]
or launch the MATLAB executable directly as:
open -n /Applications/MATLAB_R2013a.app
or by executing the binary from the command line
/Applications/MATLAB_R2013a.app/bin/matlab
Run the binary located at
C:\Program Files\MATLAB\R2013a\bin\matlab.exe
Do not use MGet
on MATLAB objects, or data structures that contain custom classes as elements. On OS X and Unix this will crash the MATLAB process because of a bug in the MATLAB Engine interface. For example,
m = containers.Map('a',1); s = struct('a',1, 'b',m);
Now running MGet["m"]
will crash MATLAB because m
is an object. MGet["s"]
will crash because s
contains an object.
All the limitations of the MATLAB Engine interface apply to MATLink. The most noticeable of these is that HFD5 based .mat
files cannot be read. Quoting the MATLAB documentation,
As of R2013a, MATLAB does not save .mat
files in this format by default, unless its settings are changed.
MGet
and MSet
do support Unicode strings, and will preserve Unicode characters. However, MEvaluate
will not preserve unicode characters in its output. MEvaluate
should handle Unicode input correctly. If you discover a situation where it does not, please report it.
The reason unicode output needed to be disabled for MEvaluate
is that MATLAB's C API is unpredictable and may not produce correct unicode output depending on version and operating system.
MEvaluate["s='Paul Erdős'"] (* Unicode input *) (* Out: s = Paul Erd!s *) MGet["s"] (* Out: Paul Erdős *)
In MEvaluate
's output Unicode in mangled, however, MGet
transfers it correctly.
A workaround is using evalc
. This is not used in MATLink because of unsolved issue #29.
cd
) MATLAB into directories that have non-ASCII characters in their path name. At the moment, the following workaround is available:
MEvaluate["feature('DefaultCharacterSet', 'windows-1252')"] MFunction["cd"]["\\path\\to\\directory"]It may be necessary to use your system's default encoding instead of
windows-1252
. To find what it is, evaluate feature('DefaultCharacterSet')
in a standalone (non-MATLink) MATLAB session.