Wednesday, June 25, 2008

How to include Matlab source code in a LaTeX document

It would be nice to have a simple way of including Matlab source code in LaTeX documents. Fortunately, Florian Knorn has made an excellent solution with his LaTeX style-file (.sty), which can be downloaded (mcode.sty) at MATLAB Central.

You may want to open mcode.sty in a text editor for details on its usage. Basically, what you need to do, is as follows:
  1. Place mcode.sty in the same folder as your tex-file, or add it to your path (see the documentation of you TeX-installation).
  2. Add
    \usepackage[options]{mcode}
    to the preamble of your tex-file. Options include:
    - bw if you intend to print the document (highlighting done via text formatting (bold, italic) and shades of gray)
    - numbered if you want line numbers
    - framed if you want a frame around the source code blocks
    - final if you have "globally" set the draft option, the listings package will not output the code at all. To force it to do so anyway, load this package with the final option (passes the final option on to listings).
  3. Include Matlab source code in your tex-file by either including the entire *.m source file
    \lstinputlisting{/path_to_mfile/yourmfile.m}
    or placing snippets of source code in a lstlisting environment.
    \begin{lstlisting}
    % Example Matlab code for calculating hypotenuse
    % § $c = \sqrt{a^2+b^2}$ §
    a = 3;
    b = 4;
    c = sqrt(a^2+b^2);
    \end{lstlisting}
  4. Note: Inside code blocks you can 'escape' to LaTeX mode by using § YOUR LATEX CODE §, which is especially useful in comments.
In case the link to mcode.sty breaks in the future, you can download the style file below. Enjoy!
mcode.sty

No comments: