Publishing Matlab code to pdf

This is a short tutorial on how to publish Matlab code to a .pdf file.

Make sure your code is ready to publish

Errors

Make sure you don’t have any errors before publishing! If you try to publish code with errors, some output will not be included in the published pdf – especially figures!

Command Window outputs

Also make sure results you’d like displayed in your published pdf are displayed in the Command Window when you Run your .m file. To make something print to the Command Window, use one of the following methods:

  • Leave off the semicolon ; at the end of the line.
  • Use the disp() command.
  • Use the sprintf() command (for formatted printing). (Documentation here.)

Code cells

I strongly recommend using code cells. These are easy to insert with %% at the beginning of a line (note the space after). Here’s an example of two code cells.

%% Problem 1
clear % clears variables
x = 5

%% Problem 2
clear % clears variables

y = x^2

When this is published, two sections are created in the published pdf, and the code of the cell is followed by the Command Window output (and/or figure) from that code.

Publish settings

Under the Publish tab, the Publish button has a drop-down menu that includes Edit Publishing Options .... Under the dialog that pops up, the Output settings>Output file format setting can be changed by clicking the current format and selecting another – choose pdf. The setting right below this, Output folder can also be changed, if desired.

Publish

The Publish button (in the dialog and also in the Publish tab) will now produce a pdf file in the specified location (by default, the html folder of the working directory).

Be sure to inspect the published pdf to make sure it includes all code, output, and figures you expect. If you need to edit anything, do so in your .m file and re-Publish. It will overwrite your old published file.

An example m-file

Here’s a sample m-file, which includes local functions.

%% Preliminaries
clear; close all

%% Problem 1: using local functions

x = 5                  % this will print
y = myfun(x);          % not this
anotherfun(x,y)        % but this will too

%% Problem 2: plotting
clear % clears variables

x = linspace(0,10,100);
y = sqrt(x);

figure
plot(x,y)


%% Local functions

function out = myfun(in)
% MYFUN squares in
  out = in^2;
end

function out = anotherfun(in1,in2)
% ANOTHERFUN multiplies in1 and in2
  out = in1*in2;
end