user1916616
user1916616

Reputation: 31

Parallel code for matrix multiplication in matlab

I want to run the code for matrix multiplication in parallel in Matlab. I have written the sequential code for it. I have used 'spmd' method to run it in parallel. But, execution time of parallel code is more than the sequential code. My motto is to reduce the execution time my running the code in parallel. I don want to use Inbuilt functions for multiplication, as i want to remove the dependency in for loops and run it. how can i do it?? I have tried fallowing code.. Please help me out..

a=[1,2,3,4;5,6,7,0;8,9,10,11;12,13,14,15];
b=[1,2,3,4;5,6,7,0;8,9,10,11;12,13,14,15];
warning off all;      
%Sequential code
tic
  for i=1:4
  for j=1:4
       sum=0;
       for k=1:4
           sum=sum+(a(i,k)*b(k,j));
       c(i,j)=sum;
       end;
  end;
  end;
  time1 =toc

  %parallel code
  matlabpool('open');
tic
spmd
for i=1:4
  for j=1:4
       sum=0;
       for k=1:4
           sum=sum+(a(i,k)*b(k,j));
       c(i,j)=sum;
       end;
  end;
  end;
 end;
time2 =toc

The output i got was.. time1 for sequencial and time2 for parallel

matrix

time1 =

0.0041

Starting matlabpool using the 'local' profile ... connected to 2 labs.

time2 =

0.6950

>> 

Upvotes: 1

Views: 2473

Answers (1)

High Performance Mark
High Performance Mark

Reputation: 78306

Extended comment rather than an answer:

  • Your test matrices are very small; any possible speed-up in execution will be overwhelmed by the overhead of starting a parallel execution pool;
  • You don't seem to initialise your output matrix c; creating a matrix dynamically as your code suggests is known to be much slower than updating a previously-created matrix. Try c = zeros(grows,ncols) to start with.
  • I believe that recent editions of Matlab will automatically multi-thread straightforward matrix multiplications, you face a real challenge trying to write a function of your own which matches the native approach for speed.

Upvotes: 1

Related Questions