120

This question led to a new package: matlab-prettifier

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?

1
  • 2
    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
    Commented May 1, 2013 at 16:00

4 Answers 4

95

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):

enter image description here

5
  • 1
    fyi, I get "if" in blue, but "end" in red, for the same "if else end" block. This is texlive 2013 using miktex. Screen shot: !Mathematica graphics other than this, it looks good.
    – Nasser
    Commented Apr 2, 2014 at 4:53
  • 2
    @Nasser That's because of the emph line. Remove it. Of course, I recommend you use the matlab-prettifier package instead :)
    – jub0bs
    Commented May 20, 2014 at 15:14
  • Is there a way to change the font that listings uses? Commented Jun 8, 2015 at 12:39
  • 1
    Is it possible to change the font to the one from \texttt ?
    – JSycamore
    Commented Sep 1, 2017 at 20:53
  • @Vivi is there any way to remove the numbers that comes up to the left of the output?
    – Zeno San
    Commented Sep 4, 2022 at 13:35
91

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.
  7. system commands.

Additional features include

  • three predefined styles: standard, black & white, and a MatlabLexer-like style for mimicking Pygments (minted) output,
  • seamless compatibility with listings' environments and macros,
  • manual highlighting of variables with shared scope,
  • manual highlighting of unquoted strings,
  • a macro for easily typesetting placeholders in code snippets,
  • automatic scaling of inline code according to its surroundings,
  • an option to only print the header of a Matlab function (see this).

matlab-prettifier is available on CTAN and in both TeX Live and MiKTeX. If you wish, you can grab the development version from the GitHub repository.

Some examples

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

person.m (matlab-prettifier) person.m (Matlab editor)

sample.m (matlab-prettifier) sample.m (Matlab editor)

code snippet with placeholders (matlab-prettifier)

Code

\documentclass{article}

\usepackage[T1]{fontenc}
\usepackage{bigfoot} % to allow verbatim in footnote
\usepackage[numbered,framed]{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...
!gzip sample.m
% ... 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\mlplaceholder % shorter macro
\lstMakeShortInline"

\lstset{
  style              = Matlab-editor,
  basicstyle         = \mlttfamily,
  escapechar         = ",
  mlshowsectionrules = true,
}

\begin{document}

\lstlistoflistings

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

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

\lstinputlisting[caption = {Sample code from Matlab}]{sample.m}
\pagebreak

\begin{lstlisting}[caption = {For educational purposes}]
% example of while loop using placeholders
while "\ph{condition}"
  if "\ph{something-bad-happens}"
    break
  else
    % do something useful
  end
  % do more things
end
\end{lstlisting}

\end{document}
19
  • 13
    Though I hate matlab truly, this is still quite cool output
    – percusse
    Commented Feb 6, 2014 at 0:07
  • 4
    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.
    – jub0bs
    Commented Feb 8, 2014 at 3:24
  • 2
    @dustin Basically, yes. Using it is no more complicated than loading a listings style. Try \lstset{style=Matlab-editor} in your preamble, and then \lstinputlisting{mycode.m}. Or, if you have listings in other programming language, use \lstinputlisting[style=Matlab-editor]{mycode.m}.
    – jub0bs
    Commented Apr 27, 2014 at 16:07
  • 1
    @Jubobs +1 great package. looks like you've changed snippetPlaceholder to mlplaceholder, not sure if edit is appropriate here. (at least, snippetPlaceholder is undefined, but i don't know latex) Commented Sep 16, 2014 at 12:08
  • 1
    @user3125280 Thanks. Yes, good catch. The macro for placeholders is indeed called \mlplaceholder, now; I just forgot to change the name in this answer. Fixed.
    – jub0bs
    Commented Sep 16, 2014 at 12:23
38

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.

enter image description here

\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

6
  • 4
    Not fair. Now that I see your answer I am not quite so proud of my code anymore :(
    – Vivi
    Commented Nov 5, 2012 at 8:43
  • The best way! Great package.
    – osjerick
    Commented Nov 25, 2013 at 17:39
  • 2
    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.
    – jub0bs
    Commented Dec 12, 2013 at 0:29
  • 1
    @Jubobs It will be awesome!
    – osjerick
    Commented Dec 13, 2013 at 16:38
  • 1
    @ZenoSan: Try without the numbered option for the package.
    – Werner
    Commented Sep 5, 2022 at 7:51
-3

Did you try

\begin{verbatim}    
Matlab code 
\end{verbatim}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .