Stuart’s MATLAB Videos

Watch and Learn

This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Simplify, simplify, simplify 1

Posted by Doug Hull,

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?
    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.

1 CommentsOldest to Newest

Steve L replied on : 1 of 1
Just be careful when you substitute in new variable names (as in your third point) that you don't accidentally introduce a bug (as in your third point.) Compare: rand(1, 12) % Creates a matrix of size [1 12]rand(1:12) % Creates a LARGE array of size [1 2 3 4 5 6 7 8 9 10 11 12] ... if it can MATLAB will happily do (or try to do) what you TELL it to do ... which may not be what you WANT it to do.

Add A Comment

Your email address will not be published. Required fields are marked *

Preview: hide