Disclaimer: This is my best guess about what is happening, but I donβt know exactly what is happening under the hood of Matlab. Update: An EitanT comment states that my guess is most likely incorrect.
I think the Matlab JIT engine performs optimization in some of these cases, but not all.
When you have a loop in which a variable is created but never used, the JIT engine does not worry about creating this variable again and again. He just does it once. All this will be fast:
% this calls 'ones' once for i = 1:100, x = ones(10000,100); end
But if you create a variable and then use it, say, passing it to a function, that variable is created every time. It takes longer, obviously.
% this calls 'ones' every iteration to pass to `full` for i = 1:100, x = full(ones(10000,100)); end
source share