Tutorial

How to Add Help Documentation to a Function in MATLAB

The help documentation of a function is specified as a contiguous block of comment lines located immediately after the function definition line.

Preparation

Consider a simple function that sums two scalar numeric values:

function R = mysum(x,y)
R = x + y;
end

Description

A function is incomplete if it does not state clearly how to use it. The help documentation of a function should include:

  • The purpose of the function
  • A description of each supported syntax
  • Examples on how to use the function
  • Links to related resources
  • Any other relevant information

Style

Use a uniform style to document your functions. I recommend that you follow the style used by The MathWorks to document its own functions.

  • The first line includes the name of the function and a brief description
  • The Examples section begins with % Example or % Examples
  • Specify the name of related functions in a line that begins with % See also

The best way to gain skills in this matter is inspecting the source code of the functions available in the MATLAB installation. To do so, use the functions type or edit.

% Show the file 'imread.m' in the Command Window
type imread;
% Open the file 'imread.m' in the Editor
edit imread;

Example

The function mysum is properly documented here. Save the file ‘mysum.m’ in the current directory or in a folder residing in the search path, and execute this code to show its help documentation.

help mysum;
Learn here how to get help using the functions help and doc.

Further reading

I recommend the following books to learn more on functions and the help system in MATLAB.

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    This book was the winner of a Textbook Excellence Award. The sixth chapter covers user-defined functions, scope of variables, debugging, and other aspects related to the development of MATLAB programs.

  2. MATLAB for Engineers (5th Edition)

    This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. The third chapter explains the help feature, and the sixth chapter covers various topics related to functions.

I also recommend the other tutorials in this series.

Source code

I hope you have learned how to add help documentation to a function in MATLAB. The source code developed in this tutorial is available at this page.

Share

Your friends may need this knowledge to complete a task. Share this tutorial.