# How to include MATLAB code in LaTeX documents

Many packages exist that allow you to include source code of different programming languages into LaTeX document. The most popular once are probably listings and fancyvrb. However, due to their aim for being as general as possible, including MATLAB source code with the right color and markup can be tedious task. Fortunately, Florian Knorn over at MATLAB Central developed a simple style file that does this for you: meet mcode.

## Set up

Download mcode.sty by clicking this link to the MATLAB Central File Exchange. If that link every breaks down, I’ve uploaded the file to the howtoTeX.com server as well: here.

Now, put the mcode.sty file in the same folder as the (master) .tex file you’re compiling. Also include the following line of code in your preamble:

\usepackage[]{mcode}

Some options could be added between the square brackets:

• bw: For black and white printing (highlighting will be done based on grayscale)
• numbered: For numbered lines
• framed: Puts a frame around each piece of code
• final: This one is for the case where the draft option is enable in the documentclass. The package will then output no code at all, unless the final option is included.

Note that the mcode package is based on the listings package (it just includes some predefined setup such that the markup and color is according to the MALTAB standard).

## Usage

Including MATLAB code can be done in two ways. First, just including the code by copy and pasting:

\begin{lstlisting} a = 1; % MATLAB comment b = 2; c = a^2 + b^2; \end{lstlisting}

The second option is to include the source code right away from the .m file:

\lstinputlisting{/path_to_mfile/my_mfile.m}

That’s all about the mark up of MATLAB source code in LaTeX documents.

1. Franklyn says:

This seems to have issues with the single quote transpose operator. any fix for that ?

2. Velibor says:

I followed the “cookbook” step by step but for me it doesn’t work, in the place of the text where the script should be I have blank paper or some dashes… weird. Anyone know whats going on?

3. If it just contains settings for Matlab, best would be to submit an official patch to the maintainer.

As far as I can tell the current solution is quite sub-optimal if one has listings from different languages. Besides that it would be a good idea to keep it in one package.

• Frits says:

I agree. However, this is a way to go when you just want to display some MATLAB source code in the correct markup without setting up the style yourself. It could be useful for (lab) reports and homework assignments.

4. Ben Abbott says:

Will the mcode.sty file be added to CTAN?