套件清單中的多行 Matlab 註釋

套件清單中的多行 Matlab 註釋

我正在使用套件列表在我的報告中包含一些 Matlab 程式碼。它適用於以以下開頭的註釋,%但不能識別多行註釋%{ ... %}

\usepackage{listings}
\lstset{language=Matlab}
...
\begin{lstlisting}
% normal comment
MATLAB code
%{
This is
a multiline
comment
%}
function [x,y] = test(x)
\end{lstlisting}

給出

在此輸入影像描述

代替

在此輸入影像描述

在Matlab中。

我該如何改變才能\lstset使其發揮作用?

答案1

我的建議是使用該套件matlab-prettifier,它基於'語言定義listings,但為 MATLAB 程式碼提供了超出這些功能的增強功能(包括對區塊註解的支援):listingsMatlab

\documentclass{article}
\usepackage{matlab-prettifier}
\lstset{style=Matlab-editor}

\begin{document}
\begin{lstlisting}
% normal comment
MATLAB code
%{
This is
a multiline
comment
%}
function [x,y] = test(x)
\end{lstlisting}
\end{document}

在此輸入影像描述

如果由於某種原因,您必須使用listings該語言的現有實現Matlab,則可以透過設定包的morecomment鍵來添加對區塊註釋的支援:

morecomment=[s]{\%\{}{\%\}}

在這裡,[s]表示我們正在尋找兩個分隔符,第一個用於打開區塊註釋,第二個用於關閉它。以下大括號組分別包含區塊註解的開始和結束分隔符號。請注意,在定義註解分隔符號時,百分號和單獨的開/閉大括號都必須用反斜線轉義。

\documentclass{article}
\usepackage{listings}
\lstset{
  language=Matlab,
  basicstyle=\ttfamily,
  morecomment=[s]{\%\{}{\%\}},
}

\begin{document}
\begin{lstlisting}
% normal comment
MATLAB code
%{
This is
a multiline
comment
%}
function [x,y] = test(x)
\end{lstlisting}
\end{document}

在此輸入影像描述

相關內容