When to break the MATLAB rules?
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(4 个)
James Tursa
2011-5-12
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 个评论
Matt Fig
2011-5-12
1 个评论
Jan
2011-5-14
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
2011-5-12
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!