The standard way of exporting figures from MATLAB to LaTeX is to use the builtin print command to export the figure to an eps file using:

print -depsc $filename

Unfortunately figures exported this way generally do not look like the original MATLAB figures. The aspect ratio is different and the fonts are too small. This can be overcome by tweaking the paper size, the font size and the line thickness but the process is fiddly and resulting eps files are hard to use since alternative TeX compilers like XeTeX and LuaTeX do not support eps files out of the box.

It is possible to save MATLAB figures as pdf files using print -dpdf $filename. This allows you to use XeLaTeX and LuaLaTeX but the other issues are not solved.

MATLAB can also save figures as png files. The resulting files actually look like the figures they were saved from but this is not recommended for publication quality graphics as high resolution images are often larger than their pdf/eps equivalents.

Enter matlab2tikz. This package translates MATlab figures into tikz graphics using pgfplots for direct inclusion into LaTeX documents. tikz is a TeX package used to generate graphics whilst pgfplots is a LaTeX package that provides convenient primitives for drawing plots. The resulting files are easy to use and modify. Additionally since they are just LaTeX code they are typeset with the rest of document and use the same fonts and font sizes. This makes them fit in a lot better and makes changing the document font or style easy since it doesn't require you to also edit your figures to change the font ! As an added bonus this also allows us to change the size and aspect ratio of our plots without having to regenerate them !

Basic Usage

To use matlab2tikz you need to download the package and place it on you MATLAB path. Once MATLAB can find it saving your figures is as simple as calling matlab2tikz(filename). This will save the current figure. Your LaTeX distribution should be smart enough to do that for you once you've added the proper \usepackage directives to your preamble.

To add the figure to your LaTeX document you need to add the pgfplots package to the preamble of your LaTeX document:

\usepackage{pgfplots}
\pgfplotsset{compat=newest}
\pgfplotsset{plot coordinates/math parser=false}

To add the figure to the LaTeX document simply insert it using \input{} into a figure environment:

\begin{figure}
        \centering

        \input{filename}
        \caption{My cool figure}
        \label{fig:my_figure}
\end{figure}

If your documents contains more than a couple tikz graphics you will probably encounter the following error:

! TeX capacity exceeded, sorry [main memory size=3000000].

There are several work arounds to this problem. The simplest is to reduce the size of the generated graphics. When matlab2tikz exports your graphs it saves every single point in the dataset even if they are so close that only a fraction of them will actually be visible. The cleanfigure command provided with matlab2tikz will reduce the number of datapoints uused to draw the graph to the bare minimum required. Sometimes however it needs help: the minimumPointsDistance option tells it how far away two points must be and discards all the points in between. Obviously, this value depends on your dataset. If correctly used you can significantly reduce your file size.

If this isn't enough, the matlab2tikz wiki has some other options.

To export a figure simply run:

cleanfigure();
matlab2tikz('tikz/filename.tikz');

Advanced Usage

Editing your figures

The biggest advantage of this approach over the pdf/png options is that modifying your graphs after the fact is easy. Getting the exact look you want in MATLAB can be an exercise in frustration. pgfplots by contrast is a pleasure to work with. Most of the syntax is self explanatory and the documentation is well written.

In one of my figures for example I needed to move the legend down because it was covering the axis labels. I just had to change the line

legend style={at={(0.5,-0.03)},anchor=north}

to

legend style={at={(0.5,-0.2)},anchor=north}

Replacements like this can even be automated using MATLAB with very little code, just open the file, find the string you want to replace and close it again:

% fix the positioning of the legend in the tikz file:
src = fileread('tikz/filename.tikz');
new_src = strrep(src, ...
    'legend style={at={(0.5,-0.03)},anchor=north}', ...
    'legend style={at={(0.5,-0.2)},anchor=north}'   ...
);

fid = fopen('tikz/filename.tikz', 'w');
fwrite(fid, new_src);
fclose(fid);

Changing the aspect ratio of a figure

If you export your figures as png setting the aspect ratio is as easy as changing the resolution of the generated image. Changing the aspect ratio is not as easy when export ing them as eps/pdf files. I often had to fiddle with pbaspect and subplots to get the right result. With matlab2tikz this is quite easy.

You can pass the desired height and width of your figure to the matlab2tikz as LaTeX commands. By default the script tries to make reasonable assumptions about the width and height of your figures but this can lead to inconsistent results in some cases. If this is the case you can specify the width attribute:

matlab2tikz('filename', 'width', '\textwidth');

This also allows you to set the height of the figure as a function of the width:

matlab2tikz('filename', 'width', '\textwidth', 'height', '0.7\textwidth');

Being so explicit about the figure width is bad practice. If we decide that we want smaller or bigger figures in our document we have to go back to the script that generates the figures and change the sizes manually. A better option is to create a special length just for our figures. That way changing the size of the figures post-facto is as easy as redefining the length in our LaTeX document. To do this we need to add the following lines to the preamble:

\newlength\figureheight
\newlength\figurewidth
\setlength\figureheight{6cm}
\setlength\figurewidth{\textwidth}

This defines the lengths \figureheight and \figurewidth. We just need to tell matlab2tikz to use these instead of trying to guess:

matlab2tikz('filename', 'width', '\figurewidth', 'height', '\figureheight');

These lengths can also be redefined for just one figure in our document. If for example we want on figure to be taller we just need to redefine the length in the figure block:

\begin{figure}
        \setlength\figureheight{8cm}

        \centering
        \input{file.tikz}
\end{figure}

Closing Notes

Hopefully you are now able to produce nicer MATLAB figures with less work. If you find yourself repeating the same code often to export your figures consider wrapping your call to matlab2tikz in a helper function.

You can find mine at github