Friday, January 13, 2012

Best Practices for Programming MATLAB

Best Practices for Programming MATLAB
starLoren on the Art of MATLAB
January 13, 2012 7:21 AM
by Loren Shure

Best Practices for Programming MATLAB

I thought I would share my top goto list of things I try to do when I write MATLAB code. And checking with other MathWorks folks whose code I admire, I found they basically used the same mental list that I use. You can find blog posts on all of these topics by selecting relevant categories from the right side of The Art of MATLAB blog site.

Contents

My List of Best Practices

Clearly (at least to me), this is not everything you generally need to do. You still need to comment the code, add good help information and examples, etc. But these are the main coding practices and tools I always rely on.

  1. Vectorize (but sensibly).
  2. Use bsxfun in lieu of repmat where possible.
  3. When looping through an array, loop down columns to access memory in the same order that MATLAB stores the data in.
  4. Profile the code. I am often surprised about what is taking up the time.
  5. Pay attention to messages from the Code Analyzer.
  6. Use functions instead of scripts.
  7. Don't "poof" variables into any workspaces. Translation, don't use load without a left-hand side; avoid eval, evalin, and assignin.
  8. Use logical indexing instead of find.
  9. Avoid global variables.
  10. Don't use equality checks with floating point values.

Missing from Your List? Additions to My List?

What's on my list that you don't currently do? Do you have a major addition to my list (there can't be too many, or I won't remember to do them all!)? Let me know here.


Get the MATLAB code (requires JavaScript)

Published with MATLAB® 7.13

Best Practice


Dr. Art Trembanis
Associate Professor
CSHEL
109 Penny Hall
Department of Geological Sciences
The College of Earth, Ocean, and Environment
University of Delaware
Newark DE 19716
302-831-2498
"We shall not cease from exploration. And the end of all our exploring will be to arrive where we started and know the place for the first time."
-T. S. Eliot, Little Gidding

"Il faut aller voir" -JYC

No comments: