performancematlabmatrix-multiplicationcoding-efficiency

Fastest way to do repeated element wise matrix multiplication in MATLAB?


Given a matrix A, I need to multiply with another constant vector B, N times (N > 1 million). The size of A is 9000x1 and B is 9000x1000.

The code is currently evaluated in the following way:

for i=1:N

    A = func_temp(i); % A is 9000x1 matrix which varies with i

    %prod = A.*B; % prod is 9000 x 1000 matrix
    %sum_temp = sum(product); % sum_temp is 1 x 1000 matrix

    % Edit: suggestion by user @rahnema1
    sum_temp = A.' * B;

    % do multiple pperations with sum_temp

    result(i) = some_constant;
end

I used Profiler to see which line is taking the most time and it is the 2nd line (prod = A.*R;). The problem is that N is very large and the code is taking over several days to complete.

I am about to try the parallel computing toolbox (GPU computing), but are there any suggestions on what I can do in the basic version?

How can I reduce the run-time of such codes in MATLAB?

Edit: I have added an edit in the code as suggested in comments which reduced run-time by 33%! But it still is the most time-taking line. Are there any more suggestions?


Solution

  • Use the matrix multiplication operator:

    sum_temp = A.' * B;