tags:

views:

142

answers:

2

I latex i want to define a macro which takes three arguments: a string and two code segments. My first idea were to display the code segments using the verbatim environment, but this fails horribly with the error message

! File ended while scanning use of \@xverbatim.

Instead I have come up with the following macro.

\newcommand{\definematlabfunction}[3]{
    \noindent
    \begin{minipage}{\textwidth}
        \noindent
        #1 \vspace{0.2cm} \\
        Function definition: \\
        \texttt{#2} \vspace{0.2cm} \\
        Example usage of the function: \\
        \texttt{#3} \\
    \end{minipage}
}

Currently I use this macro like below.

\definematlabfunction
{Create a function which takes one input argument (a list of numbers) 
and returns the last five elements of this list. If the list does not contain 
five elements, the function should display a warning.}
{function res = lastFiveElements(list)}
{>> lastFiveElements(1:10) \\
ans = [6, 7, 8, 9, 10] \\
>> lastFiveElements(7:10) \\
warning}

Can I somehow avoid the double backslashes (\) while still getting the correct code formatting?

+1  A: 

It sounds like you need the fancyvrb package.

Rob Hyndman
+3  A: 

First of all you should define your main macros

\def\definematlabfunctionMain#1#2#3{    
\noindent    
\begin{minipage}{\textwidth}        
\noindent        
 #1 \vspace{0.2cm} \\        
 Function definition: \\        
 \texttt{#2} \vspace{0.2cm} \\        
 Example usage of the function: \\        
 \texttt{#3} \\    
\end{minipage}}

Then you can define \definematlabfunction using \definematlabfunctionMain

\makeatletter 
\def\definematlabfunction#1{\def\tempa{#1}\begingroup 
  \let\do\@makeother \dospecials \catcode`\{=1 \catcode`\}=2 \obeylines \@vobeyspaces
  \definematlabfunctionplus}
\def\definematlabfunctionplus#1#2{\definematlabfunctionMain{\tempa}{#1}{#2}\endgroup}
\makeatother

Now no \\ is needed.

\definematlabfunction{Create a function which takes one input argument (a list of
numbers) and returns the last five elements of this list. If the list does not contain
five elements, the function should display 
a warning.}{function res = lastFiveElements (list)}{>> lastFiveElements(1:10)
ans = [6, 7, 8, 9, 10] 
>> lastFiveElements(7:10) 
warning}
Alexey Malistov
Great solution. It works like a charm!I do have one small issue left. If the macro is used like below it works as expected. \definematlabfunction{text}{code}{code}If used a bit different with newlines between } and {, the macro throws the error "! LaTeX Error: There's no line here to end." \definematlabfunction{text} {code} {code}
midtiby