[Tex/LaTex] use to typeset MATLAB code in the document

highlightinglistingsMATLAB

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?

Best Answer

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