7

This question already has an answer here:

I need Matlab code, e.g. the one here, in LaTeX and in colour (the comment is green, for/if/else/end is blue).

% super cooles Programm
i = 1
for i = 1:10
    if i > 3
        i=i+2
    else 
        i=i+1
    end
end

I tried

`\begin{lstlisting}
code
\end{lstlisting}`

this gave me the code, but not in colour.

I tried

\lstinputlisting[language=Matlab, frame=single]{\MatlabCodeToLaTeX.m}

this gave me the error message, that LaTeX couldn't start the file.

How do I get the code properly colored?

marked as duplicate by user13907, Adam Liter, Gonzalo Medina, Werner, egreg Jul 30 '15 at 20:40

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

migrated from stackoverflow.com Jul 30 '15 at 16:46

This question came from our site for professional and enthusiast programmers.

  • Have you tried artefact.tk/software/matlab/highlight? – Josh Jul 28 '15 at 21:22
  • Also, the error with \lstinputlisting seems to imply that it just can't find the .m file; are you sure you've got the path correct? – Josh Jul 28 '15 at 21:24
  • 1
    What does the MatlabCodeToLaTeX macro do? File paths use /, macros use ``. – David Jul 28 '15 at 22:46
3

I adapted the example form TEX

\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}


\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},    
}
\begin{document}
  \begin{lstlisting}[frame=single]
    % super cooles Programm
    i = 1
    for i = 1:10
    if i > 3
        i=i+2
    else 
        i=i+1
    end
    end
  \end{lstlisting}
\end{document}

output:

enter image description here

PS: next time when there is a latex question try searching TEX first!

Not the answer you're looking for? Browse other questions tagged or ask your own question.