When to break the MATLAB rules?
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I am planning a new video for http://blogs.mathworks.com/videos. It will be about when to "break the rules".
I am looking for more examples like the following.
Two of the examples that I want to cover are:
- Vectorize
I have seen some tortured logic in the name of vectorizing code. These cases could easily be replaced with a clear, readable for loop. The coder gained nothing in speed with this, yet lost readability.
Vectorizing is the right thing to do in many cases, taking advantage of MATLAB's matrix centric view of the world. It is not always the right thing though. Since the JIT (Just In Time) compiler was introduced, the former "for loop penalty" is largely gone. Vectorizing is not always important for speed now.
- Pre-allocate vectors in for loops
For large for loops, this is the right thing to do, avoiding the churn of an ever growing matrix. However, I saw a case today where someone was doing a lot of tedious, unclear, calculations to figure out how big a matrix would be at the end of a for loop (it was not simply growing by one each time through). In the end, it looked like the matrix was never going to get bigger than 200x200. The time saved at run time was trivial. MATLAB is a dynamicaly typed language such that you do not have to worry about this kind of thing.
There are times to break these rules for readability, ease of coding, because of only marginal improvements in performance vs code complexity. Can you think of other times when "breaking the rules" is the right thing to do?
0 Kommentare
Antworten (4)
James Tursa
am 12 Mai 2011
In-place operations in mex routines when the variables are huge and you can't afford the extra copies that MATLAB would normally make in doing an operation. (It would be nice if TMW would supply some official API functions to detect sharing status etc to make this job easier for the mex programmer to avoid unwanted side effects.)
0 Kommentare
Matt Fig
am 12 Mai 2011
1 Kommentar
Jan
am 14 Mai 2011
I think, EVAL is obligatory, if you want to access a GLOBAL variable, whose name is determined dynamically, because "global(VarName)" does not work, but "eval(['global ', VarName])" does. The same for PERSISTENT.
But let me mention, that such contructs are bad programming methods in my opinion.
Sean de Wolski
am 12 Mai 2011
When trying to write code to solve some type of image processing problem, I'll start with I, then I1, then I1opened, I2, I2dilated, I3, I3nosmalljunk, I4, IstuffIcareaboutHopefully, I5
0 Kommentare
Siehe auch
Kategorien
Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!