Publishing Matlab code to pdf
- Make sure your code is ready to publish
- Publish settings
- An example m-file
This is a short tutorial on how to publish Matlab code to a
Make sure your code is ready to publish
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
.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
- Use the
sprintf()command (for formatted printing). (Documentation here.)
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 tab, the
Publish button has a drop-down menu that includes
Edit Publishing Options .... Under the dialog that pops up, the
Output file format setting can be changed by clicking the current format and selecting another – choose
Output folder can also be changed, if desired.
Publish button (in the dialog and also in the
Publish tab) will now produce a
html folder of the working directory).
Be sure to inspect the published
.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