# What can I use to typeset MATLAB code in my document?

Does anybody have a quick and easy way to typeset some relatively long MATLAB code in the appendix? I looked up a few methods, and the mcode package emerged as a possibility, but it seems to be unmaintained...

I have a ton of equations in my code, so I'd prefer a solution that avoids having to use \$ to denote equations.

Also, if possible, if there's a way to keep all of MATLAB's "natural" coding colors (e.g. green for comments), that would be great...

Any idea?

-
I used mcode for my thesis and it worked fine. Depending on what version of MATLAB you are using, it also has built-in tools for exporting the code with LaTeX markup already embedded. Look up "publish" in the MATLAB help browser. –  craigim May 1 '13 at 16:00
Consider using the matlab-prettifier package; see my answer below. –  Jubobs Feb 10 at 10:11
add comment

## 3 Answers

Here is the template I use for matlab code:

\documentclass{article}

\usepackage{listings}
\usepackage{color} %red, green, blue, yellow, cyan, magenta, black, white
\definecolor{mygreen}{RGB}{28,172,0} % color values Red, Green, Blue
\definecolor{mylilas}{RGB}{170,55,241}

\begin{document}

\lstset{language=Matlab,%
%basicstyle=\color{red},
breaklines=true,%
morekeywords={matlab2tikz},
keywordstyle=\color{blue},%
morekeywords=[2]{1}, keywordstyle=[2]{\color{black}},
identifierstyle=\color{black},%
stringstyle=\color{mylilas},
commentstyle=\color{mygreen},%
showstringspaces=false,%without this there will be a symbol in the places where there is a space
numbers=left,%
numberstyle={\tiny \color{black}},% size of the numbers
numbersep=9pt, % this defines how far the numbers are from the text
emph=[1]{for,end,break},emphstyle=[1]\color{red}, %some words to emphasise
%emph=[2]{word1,word2}, emphstyle=[2]{style},
}

\section*{Matlab Code}

\lstinputlisting{myfun.m}

\end{document}


This produced the following output (I didn't put my matlab file here but it should be clear from the output):

-
worked like a charm! Thanks alot –  suzu Oct 3 '12 at 16:21
add comment

The mcode package still supports Matlab code formatting, setting the default lstlisting environment (from listings) formatting to that of Matlab. It also provides \mcode{<code>} for inline Matlab code.

\documentclass{article}
% http://www.mathworks.com/matlabcentral/fileexchange/8015-m-code-latex-package
\usepackage[framed,numbered,autolinebreaks,useliterate]{mcode}
\begin{document}
\begin{lstlisting}
function y = myfun(aa, sigma, options)

sigma

y = aa .* pdf('logn', aa, -0.5*sigma^2, sigma)

%y = 1/(sigma.*sqrt(2.*pi)) .* exp((-((log(aa)+0.5*sigma.^2)).^2) ./ (2.*sigma.^2));
\end{lstlisting}
\end{document}


Similar reference: Inline MATLAB code

-
Not fair. Now that I see your answer I am not quite so proud of my code anymore :( –  Vivi Nov 5 '12 at 8:43
The best way! Great package. –  OSjerick Nov 25 '13 at 17:39
Unfortunately, the mcode package suffers from several limitations, one of which is that it doesn't typeset the context-sensitive end keyword correctly all the time. I'm working on a package that allows for correct syntax highlighting of Matlab listings, and I'm hoping to submit it to CTAN in the near future. –  Jubobs Dec 12 '13 at 0:29
@Jubobs It will be awesome! –  OSjerick Dec 13 '13 at 16:38
add comment

For typesetting Matlab code in LaTeX, consider using the matlab-prettifier package.

Piggybacking on the listings package, it doesn't require much configuration, and it keeps track of the context (behind the scenes) in order to highlight code as it appears in the Matlab editor. In this respect, it arguably does a much better job than the other available options (minted, listings, mcode, etc.) do.

Syntax highlighting currently performed by the matlab-prettifier package include:

1. context-insensitive keywords (e.g. for, while, break),
2. context-sensitive keywords (e.g. end, properties, events),
3. (quoted) strings,
4. one-line and block comments,
5. line-continuation tokens (...),
6. code-section titles.

Additional features include

• seamless compatibility with listings' environments and macros,
• manual highlighting of variables with shared scope,
• a macro for easily typesetting placeholders in code snippets,
• three predefined styles: standard, black & white, and a MatlabLexer-like style for mimicking Pygments (minted) output,
• compatibility with XeLaTeX and LuaLaTeX,
• partial support of Unicode, if used in conjunction with the listingsutf8. package.

I plan to submit matlab-prettifier to CTAN in the near future. In the meantime, you can grab the alpha version from the Bitbucket repo.

## Some examples

For comparison, here are some code samples as typeset by matlab-prettifier and as they appear in the Matlab editor.

## Code

\documentclass{article}

\usepackage[T1]{fontenc}
\usepackage[scaled=0.85]{beramono}
\usepackage{bigfoot} % to allow verbatim in footnote
\usepackage{matlab-prettifier}

\usepackage{filecontents}
\begin{filecontents*}{person.m}
classdef person
properties %(here, properties is a keyword)
mass=80;
height=1.80;
end
methods
function BMI = getBMI(height,weight)
BMI = person.mass/person.mass^2;
end
end
end
\end{filecontents*}

\begin{filecontents*}{sample.m}
%% Code sections are highlighted.
% System command are supported...
!touch testFile.txt
% ... as is line continuation.
A = [1, 2, 3,... % (mimicking the ouput is good)
4, 5, 6]
fid = fopen('testFile.text', 'w')
for i=1:10
fprintf(fid,'%6.2f \n', i);
end
x=1; %% this is just a comment, though
% Context-sensitive keywords get highlighted correctly...
p = properties(mydate); %(here, properties is a function)
x = linspace(0,1,101);
y = x(end:-1:1)
% ... even in nonsensical code.
]end()()(((end end)end ))))end (function end
%{
block comments are supported
%} even
runaway block comments
are
\end{filecontents*}

\let\ph\snippetPlaceholder % shorter macro

\lstdefinestyle{myMat}
{
language             = Matlab-pretty,
numbers              = left,
frame                = single,
escapechar           = ",
breaklines           = true,
showcodesectionrules = true,
}

\lstMakeShortInline[style=Matlab-standard-style]"

\begin{document}

\lstlistoflistings

\lstinputlisting
[
style   = myMat,
caption = {Some class definition},
]{person.m}

Before you use any "for"~loop, refresh your memory on Matlab blocks.%
\footnote{Any occurence of the "for" must have a matching "end".}

\lstinputlisting
[
style   = myMat,
caption = {Sample code from Matlab},
]{sample.m}

\pagebreak

\begin{lstlisting}%
[
style   = myMat,
caption = {For educational purposes},
]
% example of while loop using placeholders
while "\ph{condition}"
% do something useful
if "\ph{something}"
break
else "\ph{something\_else}"
continue
end
% do more things
end
\end{lstlisting}

\end{document}

-
Though I hate matlab truly, this is still quite cool output –  percusse Feb 6 at 0:07
Great! Thanks. I think you should upload it to Mathworks File Exchange. –  OSjerick Feb 7 at 4:49
I myself find Matlab frustrating in many ways, but it's still a great tool for prototyping number-crunching stuff. What spurred me into writing matlab-prettifier is that none of the existing tools do a great job at replicating the syntax highlighting of the Matlab editor, and I think Matlab beginners learn more effectively if they're exposed to code that is highlighted in a consistent manner, whether is be in the Matlab editor or in a PDF. –  Jubobs Feb 8 at 3:24
Looks rather nice - the main differences between the matlab window and the output (I know matching colours was the request) look to be the font weight and line spacing - and the latter could be tightened to match. –  Chris H Feb 10 at 14:01
@ChrisH I used Courier in my listings, whereas Matlab uses its proprietary (I think) Monospaced font by default. However, because matlab-prettifier is compatible with XeLaTeX/LuaLaTeX, you can always set a different monospace font for your listings, one closer in appearance to Matlab's Monospaced, if you so wish. –  Jubobs Feb 10 at 14:29
show 5 more comments

## protected by Community♦Feb 11 at 9:40

This question is protected to prevent "thanks!", "me too!", or spam answers by new users. To answer it, you must have earned at least 10 reputation on this site.