如何將 Matlab 程式碼包含到 LaTeX 中?

如何將 Matlab 程式碼包含到 LaTeX 中?

我需要Matlab 程式碼,例如這裡的LaTeX 程式碼和彩色程式碼(註解是綠色的,for/if/else/end 是藍色的)。

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

我試過

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

這給了我代碼,但不是彩色的。

我試過

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

這給了我錯誤訊息,LaTeX 無法啟動該檔案。

如何讓程式碼正確著色?

答案1

我改編了範例表格泰克斯

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

輸出:

在此輸入影像描述

PS:下次遇到 Latex 問題時,先試著搜尋 TEX!

相關內容