MATLAB: Matrix multiplication result – where does it go

memorymtimessubsasgnsubsref

I've been curious, after various recent observations, about whether matrix multiplication always allocates fresh memory for its output. For example, suppose I do something like
A(:,1)=B*x;
Is this equivalent to
z=B*x; %memory allocated here

A(:,1)=z;
Or, does the output of B*x get directly generated in the memory locations occupied by A(:,1)? Obviously, the latter would be more efficient, but I wasn't sure how it worked. I know for example that this
A(1,:)=B(1,:)*x;
is equivalent to
z=B(1,:); %memory allocated here
A(1,:)=z*x;
so obviously not everything is as well optimized as it could be.

Best Answer

Interesting question. The answer will probably depend on MATLAB version and JIT settings. TMW likely keeps stuffing more & more optimization like this into their JIT code with each version release. (E.g., the in-place operations that can sometimes take place for certain function call syntaxes.) Probably the only way to get any insight into it would be to do some timing and/or memory tests using very large arrays.
(That reminds me ... I need to finish testing & upload the new version of MTIMESX which allows in-place operations)