Publishing MATLAB Code - hasselmonians/knowledge-base GitHub Wiki

MATLAB code can be published to a pdf for easy storage and sharing of code. The published document can include plots and data computed at run-time.

Dependencies

You will need a LaTeX distribution like TeX Live, MacTeX, or MiKTeX. You will also need the mtools package for MATLAB. Make sure that the mtools package is on your MATLAB path, e.g.

addpath('path/to/srinivas.gs_mtools')
savepath

and that whatever TeX distribution you have comes with the XeLaTeX engine (all three mentioned above do).

Finally, you need a stylesheet, like this one here.

First Steps

Write your MATLAB script in some folder on your computer. Let's call it myScript.m. Your file should look like this:

pdflib.header();

%% Section name
% Some descriptive text
% Here is an inline equation: $E = mc^2$.
% Here is a block equation
% $$ E = mc^2 $$
% Here is some *bolded* and _italicized_ and |monospaced| text.

% some actual matlab code
figure;
plot(1:10, rand(10));

figlib.pretty();
figlib.tight();

pdflib.snap();
delete(gcf);

% and then somewhere at the bottom something like this:

%% Version Info
% The file that generated this document is called:
pdflib.footer();

The header and footer set up the correct options for publishing. There are a host of markup options you can use in MATLAB that you can see here.

When a figure is produced, it is important to use pdflib.snap() afterwards and then delete() the figure if you aren't ready to publish.

Changing the stylesheet

The stylesheet is a pretty good general format, but you will want to change the "title" and "author" lines to reflect your own topic.

\title{Awesome MATLAB notebook}
\author{Your Name Here}

Publishing your document

When you are ready to publish, first commit all changes (if you're in a git repository), and then type

pdflib.make

This function will try to build the most recent eligible script called. It will also try to find the correct stylesheet.xsl document. For best results, keep your stylesheet and your script in the same folder, and run pdflib.make from there after testing your script.

cd myContainingFolder
myScript
pdflib.make

The pdf will appear in a containing html folder. It will be marked with a list of all git repository dependencies and their exact commit hashes, so you will always know how to reproduce the exact figures. Furthermore, a log of older pdfs will build in an Archive folder.

If you run

pdflib.make('dirty', true)

you will get pdfs of each figure as well.