Search code examples
matlabloopsmatrixoptimizationmatrix-multiplication

Tips to reduce the execution time of this Matlab loop containing several matrix operations


I am trying to evaluate the matrices Y(p,k) and Z(p,k) using the following simplified Matlab code.

They depend on some matrices A(j,k), B(j,p) and C(j,k) which I am able to precalculate, so I have just initialised them as random arrays for this MWE. (Note that B is a different size to A and C).

Nj = 5000;
Nk = 1000;
Np = 500;  % max loop iterations

A = rand(Nj,Nk);  % dummy precalculated matrices
B = rand(Nj,Np);
C = rand(Nj,Nk);

Y = zeros(Np,Nk); % allocate storage
Z = zeros(Np,Nk);

tic
for p = 1:Np
   
    X = A .* B(:,p);
    Y(p,:) = sum( X , 1 ); 
    Z(p,:) = sum( C .* X , 1 );
    
end
toc    % Evaluates to 11 seconds on my system

As can be seen above, I am repeating my calculation by looping over index p (because the matrix B depends on p).

I have managed to get this far by moving everything which can be precalculated outside the loop (contained in A, B and C), but on my system this code still takes around 11 seconds to execute. Can anyone see a way in Matlab to speed this up, or perhaps even remove the loop and process all at once?

Thank you


Solution

  • I think the following should be equivalent and much faster:

    Y = B' * A;
    Z = B' * (A.*C);
    

    Notes:

    • If B is complex-valued then you should use .' for transposition instead.
    • You may also want to pre-compute B directly in transposed form (i.e. as a Np by Nj matrix) to avoid the transposition altogether.
    • If C is not needed anywhere else, then pre-compute it as A.*C instead in order to avoid the extra element-wise multiplication.