Typesetting Long Matlab Code Snippets In Latex Documents

Formatting Code Blocks in LaTeX

LaTeX provides several methods for formatting code blocks within documents. When including long snippets of MATLAB code in a LaTeX document, proper formatting helps improve readability and makes the code easier to follow.

Using the verbatim environment

The verbatim environment is useful for displaying raw code or text without interpretation. It disables special LaTeX characters and whitespace formatting, displaying content exactly as typed inside the environment.

\begin{verbatim}
for i = 1:10
    a(i) = i; 
    fprintf('Iteration %d\n', i);
end
\end{verbatim}

The main downside when including long MATLAB snippets is that lines will not wrap once they extend past the document margins. Very long lines can overflow into the page border, making code difficult to read.

Customizing the formatting with fancyvrb

The fancyvrb LaTeX package provides extensions to the base verbatim environment for better code formatting. Key features include:

  • Line wrapping for long code lines
  • Automatic indentation and spacing preservation
  • Syntax highlighting when used with the listings package
  • Line numbering for easy reference

To enable fancy verbatim features, include the \usepackage{fancyvrb} command in the LaTeX preamble before defining the document. Then code can be wrapped in the improved Verbatim environment provided by fancyvrb.

\usepackage{fancyvrb}
\begin{Verbatim}[commandchars=\\\{\}]
\addpath{'C:\Program Files\MATLAB\toolbox\images'};
RGB = imread('trees.png');
figure; imshow(RGB); title('Example Image');
\end{Verbatim}

Line numbering and basic styling

Line numbering is enabled by passing the [numbers=left] option to the Verbatim environment. Numbers can also be right aligned by setting [numbers=right]. Number styling can be customized by redefining the \theFancyVerbLine command.

\begin{Verbatim}[numbers=left,numbersep=8pt,
  commandchars=\\\{\},codes={\catcode`$=3\catcode`^=7}]
for ^i = 1:$N^2$
    ^x(^i) = ^i * random();\^ 
    fprintf('Saved value %f\textbackslash n', ^x(^i));
end
\end{Verbatim}

Other style elements like the background, font family and size, frame around the environment border, and space between lines can also be configured using fancyvrb package options.

Breaking long lines of code

LaTeX documents restrict code width to the text block margins. But MATLAB code often has extremely long command chains that extend well past a typical LaTeX line length. To handle wide MATLAB snippets, long command chains need to break gracefully without misalignment or lost characters at the wrap point.

Fortunately, fancyvrb's line breaking algorithm handles edge cases well. Break points are inserted between parameters were whitespace already exists in the original code. If a long string literal gets split, the line break is still seamless since the text continues uninterrupted. The line numbers also help reconnect the partially visible line segment with the wrapped continuation line.

Integrating MATLAB Code

A major use case for LaTeX is preparing scientific reports, publications and analyses based on computational tools like MATLAB. Seamlessly embedding MATLAB output and images alongside LaTeX content is key for technical and academic writing.

Loading MATLAB output directly

To insert textual MATLAB output like numerical data, messaging printouts, or calculation results, the \verbatiminput command from fancyvrb can import content saved to an external file.

MATLAB script to generate output:
x = 0:.01:20;
f = exp(-x/5).*sin(x);
fprintf('Function extremes at: %f, %f\textbackslash n', x(findpeaks(f)), x(findpeaks(-f)));

LaTeX code to load output verbatim:  
\begin{verbatiminput}{output.txt}
\end{verbatiminput}

The file path passed to \verbatiminput must match the location where the MATLAB output text file is saved. This cleanly presents complex numerical output and text messages without having to manually copy paste content into LaTeX.

Displaying code side-by-side with output

To discuss and explain MATLAB algorithms within a LaTeX report, the input code and resultant output often need to be presented side-by-side. The listings package supports this usage via the \lstinputlisting command for importing code files.

\begin{minipage}[t]{0.45\linewidth}
  \lstinputlisting[language=Matlab]{code.m} 
\end{minipage}
\hfill
\begin{minipage}[t]{0.45\linewidth}
\begin{verbatiminput}{output.txt}
\end{verbatiminput}  
\end{minipage} 

Here two minipage environments are used to position content side-by-side, with the code file imported on the left and output text imported on the right. The code can be discussed and explained by referring to the line numbers added by listings.

Automating saving and loading of MATLAB files

Manually running MATLAB code and saving output files becomes inefficient when routinely compiling LaTeX documents. Instead, the generation of plots, images and output text can be automated via MATLAB scripts. The publish function handles this by running specified code and saving figures or data to file.

\begin{lstlisting}[language=Matlab]
data = randn(100,1);
histogram(data)
title('Normal Distribution') 

publish('hist_figure.png'); 
fprintf('Mean value: %f\n', mean(data));
publish('hist_output.txt');
\end{lstlisting}

The LaTeX document can then load the published files without needing to manually re-execute MATLAB and save data each time. This automates report generation when documents contain heavy MATLAB usage.

Additional Tips and Tricks

Further best practices that streamline working with MATLAB code in LaTeX include...

Syntax highlighting

The listings package adds color highlighting for built-in MATLAB functions and programming elements like comments when importing .m files. Customization options enable tweaking styles to better distinguish keywords and components.

\begin{lstlisting}[language=matlab,
  keywordstyle=\color{blue},
  commentstyle=\color{green}\itshape,
  stringstyle=\ttfamily\color{red}] 
\end{lstlisting}

Hyperlinking to external code files

Lengthy standalone MATLAB scripts and functions can be stored as separate files then referenced via hyperlinks for easier online navigation of complete code projects.

The \href{run_analysis.m}{main analysis code} invokes the \href{helper_fcns.m}{helper functions}.

Captions and cross-referencing

Figures, tables, and listings generated from MATLAB can numbered and captioned for easier reference inline or across sections.

\begin{lstlisting}
  ...
\end{lstlisting} 

See Listing \ref{alg1} for the numerical optimization approach.  

Captions and automatic numbering help document complex file interdependencies and execution flow across long MATLAB code bases.

Leave a Reply

Your email address will not be published. Required fields are marked *