For programs that have more than a couple of lines it is important to include comments. Comments allow other people to know what your program does and they also remind yourself what your program does if you set it aside and come back to it later. It is best to include comments not only at the top of a program, but also with each section. In MATLAB anything that comes in a line after a
% is a comment.
For a function program, the comments should at least give the purpose, inputs, and outputs. A properly commented version of the function with which we started this section is:
function y = myfunc(x)
% Computes the function 2x^2 -3x +1
% Input: x -- a number or vector;
% for a vector the computation is elementwise
% Output: y -- a number or vector of the same size as x
y = 2*x.^2 - 3*x + 1;
end
For a script program, there should be an initial comment stating the purpose of the script. It is also helpful to include the name of the program at the beginning. For example:
% mygraphs
% plots the graphs of x, x^2, x^3, and x^4
% on the interval [-1,1]
% fix the domain and evaluation points
x = -1:.1:1;
% calculate powers
% x1 is just x
x2 = x.^2;
x3 = x.^3;
x4 = x.^4;
% plot each of the graphs
plot(x,x,'+-',x,x2,'x-',x,x3,'o-',x,x4,'--')
The MATLAB command
help prints the first block of comments from a file. If we save the above as
mygraphs.m and then do
it will print the first block of comments into the command window:
>> help mygraphs
mygraphs
plots the graphs of x, x^2, x^3, and x^4
on the interval [-1,1]