Skip to main content

2.14) Comments


Finally, let's talk about adding comments in your scripts. Remember that a Matlab script is a series of statements saved as a .m file.

  • A script will normally perform a specific task that you might want to repeat, or share with someone.
  • It is therefore good practice to accompany Matlab statements with comments to allow you (and other users) to understand the code at a later date.
  • It is AMAZINGLY difficult to decipher code - even your own - once you have forgotten about it for a while! Omit comments at your peril...
  • A comment is a clear yet succinct piece of text that follows a percent sign "%". When Matlab executes the script it knows to ignore all text on a line following a "%".
  • As a programmer you don't want to have too many comments (perhaps not one for each statement), but you will want sufficient commentary for the script to make sense when you come back to read it later - or share it.
  • Comments can also be used to prevent sections of code from being executed. Here the effect of the "%" is to make Matlab ignore a statement. You may want to do this because the section of code is likely obsolete but you don't want to delete it yet. A large block of code can be commented out either with a "%" at the start of each line or by using "%{" and "}%" at the start and end of a block of lines.