我只想在 latex 中添加一行 Matlab 代码

我只想在 latex 中添加一行 Matlab 代码

我想显示我使用哪个命令行来获得某些特定结果。例如,我想显示此行“for i=1:100”在文本之间

我正在使用列表环境。

\documentclass[hidelinks, 12pt, a4paper, oneside]{book}
\usepackage[]{listings}
\usepackage{color} %red, green, blue, yellow, cyan, magenta, black, white
\definecolor{mygreen}{RGB}{28,100,0} % color values Red, Green, Blue
\definecolor{mylilas}{RGB}{170,55,241}
\lstset{literate=%
    {Ö}{{\"O}}1
    {Ä}{{\"A}}1
    {Ü}{{\"U}}1
    {ß}{{\ss}}1
    {ü}{{\"u}}1
    {ä}{{\"a}}1
    {ö}{{\"o}}1
    {~}{{\textasciitilde}}1
}
\lstset{language=Matlab,%
    basicstyle={\linespread{0.9}\small\ttfamily},
    linewidth=470,
    xleftmargin=25,
    xrightmargin=10,
    breaklines=true,%
    morekeywords={matlab2tikz},
    keywordstyle=\color{black},%
    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={\small \ttfamily\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{blue}, %some words to emphasise
    %emph=[2]{word1,word2}, emphstyle=[2]{style},    
}
\renewcommand{\ttdefault}{pcr}

有人能帮忙吗?谢谢您的关注。:)

答案1

您无需手动定义样式,而是可以执行以下操作:

\documentclass[hidelinks, 12pt, a4paper, oneside]{book}

\usepackage{listings}
\usepackage[framed , numbered]{matlab-prettifier}

\begin{document}

\begin{lstlisting}[style=Matlab-editor]
%This is a MATLAB environment
for i = 1:1:100
\end{lstlisting}

\end{document}

答案2

您可以将 inline 与 一起使用matlab-prettifier。以下是示例。下面的字符 (`) 表示 inline 的开始。

\documentclass[11pt]{article}
\usepackage[margin=1.2in]{geometry}

\usepackage{textcomp}           % To use with matlab-prettifier
\usepackage{listings}
\usepackage{matlab-prettifier}  % Matlab Prettifier

\lstMakeShortInline[style=Matlab-editor]`

\begin{document}
This statement `for n = 1:100,display(n),end` shows the variable `n`.
\end{document}

在此处输入图片描述

相关内容