When I started working with matlab sometime ago in the university, my supervisor would kill me if he saw any unnecessary for loop (he would ask for exchanging it for kron
or any type of indexes manipulation as possible). Later on, I was trying to avoid as much as possible any loop on matlab, searching for the darkest matlab coding ways to do black magic instead of a simple loop.
And one day I discovered the cellfun
, which made the black magic quite simplier, I could change many loops working with cells and cellfun
combo, but one day I saw one post about cellfun which made me question if my inherited matlab knowledge was true, that is: that matlab loops would always be slower than one builtin compiled function, which was something I had so much faith. I tested it in one of my implementations and in fact, the for loop would be faster! I was like, OMG, all those days doing obscure code wasted for nothing hahaha. Since that day, I stopped working that hard to try to optimize matlab code, normally it depends for each case and so on.
Today I saw this answer, which remembered my effort for avoiding as much matlab loops as possible (I don't know if that was the author will to avoid for performance, but anyway it reminded all this matlab loop performance thing). And one question came to my mind: Is cellfun better than for loops? When would that be true?