Stuart’s MATLAB Videos

Watch and Learn

Simplify, simplify, simplify

I often say that one my greatest qualifications for troubleshooting MATLAB code is that I know I am not that clever, so I have to simplify things until I can understand them easily. It works really well when debugging MATLAB code.

  • Use simpler data: Instead of using a 100,000 long vector, can you use a 10 long vector until you have the algorithm working?
  • Remove complexity: Most MATLAB ‘bugs’ can be reproduced with no more than ten lines of code. Once we remove all the extraneous lines of code, it becomes clear what is really going on. For example, a recent graphics case was brought to me. The case had nothing to do with the title, so I removed the code that created a title. Was the title hurting anything? No, it was not, but that and 30 other similar removals made the code three lines long and made the problem very evident
  • Use better variable names: I often get code to debug for people, the variable names are often distracting and take away mental energy from understanding the code. Which is easier to understand?
    plot(r287(ind:ev),hhGrams)
    
    or
    
    startIndex = ind;
    stopIndex  = ev;
    xVec        = r287;
    
    yVec       = hhGrams;
    
    plot(xVec(startIndex, stopIndex), yVec)
    
    All I did was change the names of those variables for the plotting step. Ideally, I would have had well named variables throughout my code, but at least this little corner of the code it more understandable now. This kind of simplification (even though it is more lines of code), when applied many, many times will tame complexity.
|
  • print

Comments

To leave a comment, please click here to sign in to your MathWorks Account or create a new one.