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

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


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}

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