I'm micro-optimizing an inner loop and ran into something I don't understand in the profiler (R2013b):

C is a 2x2 matrix, x and y are data, everything else is scalar. Why the difference in speeds between lines 33 and 34 which are both doing the same thing - assigning a scalar to an entry in an array. If I swap those two lines the behaviour is the same, the second one is much slower.
Is this a profiler bug or is there something going on I don't understand? The ratio is the same even when I scale up to several minutes (eg line 32 and line 34 take the same time). I can't see how any copy-on-write or similar would be triggered here so the speed difference doesn't make any sense to me. Saving the 30% here would be a big win for me.
Thanks for any help
I believe the reason that the second one is slower, is not in the contents of the line, but more in when the matrix is actually going to be used. In the first line matlab 'knows' that it does not need to do anything yet, because the next line is an independant change in C.
If you want to verify that it is not in the contents of the line, add something like C(1,1)=Cxy underneath as a third line, probably now both of the first two lines will appear fast.
Basically this means that you can probably not not increase the speed much.
Perhaps you can try logical indexing as it may be slightly faster (untested).
C([false true; true false]) = Cxy;
or perhaps linear logical indexing:
C([false true true false]) = Cxy;
For what it is worth, I would guess that the entire effect is due to the Just In Time principle that Matlab follows.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With