我已经使用过这个matlab-prettifier
包几次了。到目前为止,我只使用以下命令导入了整个 .m 文件以在我的文档中显示:
\usepackage[numbered,framed]{matlab-prettifier}
\let\ph\mlplaceholder % shorter macro
\lstMakeShortInline"
\lstset{
style = Matlab-editor,
basicstyle = \mlttfamily,
escapechar = ",
mlshowsectionrules = true,
}
在序言中:
\lstinputlisting{../mFile.m}
在文件中。
在即将进行的beamer
演示中,我只想展示部分代码,例如第 10-15 行。这是否(容易)实现?
我通常使用 documentclassmemoir
来写作。这里的解决方案是否相同/更简单?(如果存在的话。)
答案1
matlab-prettifier
建立在 之上listings
。因此,您可以使用linerange={<first1>-<last1>,<first2>-<last2>, and so on}
(这是一个listings
选项)来打印选定的行。例如:
\lstinputlisting[caption = {Sample code from Matlab with line range},linerange={3-6}]{sample.m}
sample.m
现在将打印第 3 至 6 行。
代码(来自 Jubobs 的一个旧答案):
\documentclass{memoir}
\usepackage[T1]{fontenc}
\usepackage{bigfoot} % to allow verbatim in footnote
\usepackage[numbered,framed]{matlab-prettifier}
\usepackage{filecontents}
\begin{filecontents*}{person.m}
classdef person
properties %(here, properties is a keyword)
mass=80;
height=1.80;
end
methods
function BMI = getBMI(height,weight)
BMI = person.mass/person.mass²;
end
end
end
\end{filecontents*}
\begin{filecontents*}{sample.m}
%% Code sections are highlighted.
% System command are supported...
!gzip sample.m
% ... as is line continuation.
A = [1, 2, 3, ... % (mimicking the ouput is good)
4, 5, 6]
fid = fopen('testFile.text', 'w')
for i=1:10
fprintf(fid,'%6.2f \n', i);
end
x=1; %% this is just a comment, though
% Context-sensitive keywords get highlighted correctly...
p = properties(mydate); %(here, properties is a function)
x = linspace(0,1,101);
y = x(end:-1:1)
% ... even in nonsensical code.
]end()()(((end end)end ))))end (function end
%{
block comments are supported
%} even
runaway block comments
are
\end{filecontents*}
\let\ph\mlplaceholder % shorter macro
\lstMakeShortInline"
\lstset{
style = Matlab-editor,
basicstyle = \mlttfamily,
escapechar = ",
mlshowsectionrules = true,
}
\begin{document}
\lstlistoflistings
\lstinputlisting[caption = {Some class definition}]{person.m}
Before you use any "for"~loop, refresh your memory on Matlab blocks.%
\footnote{Any occurence of "for" must have a matching "end".}
\lstinputlisting[caption = {Sample code from Matlab with line range},linerange={3-6}]{sample.m}
%% \lstinputlisting[caption = {Sample code from Matlab with line range},linerange={3-6,10-15}]{sample.m}
\lstinputlisting[caption = {Sample code from Matlab}]{sample.m}
\pagebreak
\begin{lstlisting}[caption = {For educational purposes}]
% example of while loop using placeholders
while "\ph{condition}"
if "\ph{something-bad-happens}"
break
else
% do something useful
end
% do more things
end
\end{lstlisting}
\end{document}
答案2
您可以在listings
包内使用以下语法执行此操作。
\lstinputlisting[firstline=10, lastline=15]{../mFile.m}
这将在beamer
和memoir
以及其他类别中发挥作用。
也可以看看:使用 \lstinputlisting 包含文件但仅包含某些行或行范围
Wikibooks LaTeX:源代码列表