User Tools

Site Tools


en:software:matlab:tips:index

Coding Tips

Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. John Woods

A few tips for writing code, especially that kind doing computationally costly simulations.

<note tip>None of these points is obligatory, neither is the list comprehensive. But bear in mind that its the result of personal (practical) experience (of several people) over quite some time.</note>

Coding conventions

  • Use meaningful filenames.
    • Develop a sensible directory hierarchy for your codes and projects.
    • Where possible, write reusable code and store it in a separate directory that gets added to the Matlab path.
  • Use functions rather than scripts, whereever possible.
  • Try to avoid for loops whereever possible.
    • Matlab offers you a broad range of matrix manipulation methods that are much faster in Matlab than for loops.
  • Document your code carefully.
    • Note: Even you will struggle to understand what your code does, if you look at it after two months.
    • Possibly, others want to make use of your code, at least try to understand what you did, and if necessary, adapt it for their needs.
  • Add a description of what the file does at the top of all your files.
    • Add references to papers if relevant.
  • Add a history bit at the top of all your files (below the general description).
    • At least, the date of the last modification.
    • If you modify something, add a short note what has changed (and why).
  • Use sensible names for variables.
    • It doesn't matter if they are long.
    • Where applicable, add comment lines telling what these variables are.
  • Add comment lines in the source code describing shortly what the following lines do.

If you plan to add your code or at least parts of it to a thesis:

  • Beware of the line lenghts
    • Display a vertical line for the maximum line length in your editor1)
    • Break long lines using

Results

  • Save results to a file.
    • Easiest: Save as Matlab file (“.mat”).
    • Use a proper name that allows you to easily recognise the file contents.
    • Save all the parameters you used for the calculations, and that are important to repeat it.
    • Perhaps also save a string with a description in it.
  • Save the graphics files.
    • Save as Matlab fig file (allows later modifications)
    • Save as EPS or PDF file (allows including in reports)
      • (Normally) a vector format, therefore allows scaling
  • Write short summaries.
    • Whereever possible and suitable, sum up your results for a (sub-)project before moving on to the next problem.
1)
The Matlab editor offers this possibility.
en/software/matlab/tips/index.txt · Last modified: 2020/09/30 21:35 by 127.0.0.1