title: MATLAB matrix multiplication vs for loop for each column
body: <p>When multiplying two matrices, I tried the following two options:</p>
  
  <p>1)</p>
  
  <pre><code>res = X*A;
  </code></pre>
  
  <p>2)</p>
  
  <pre><code>for i = 1:size(A,2)
      res(:,i) = X*A(:,i);
  end
  </code></pre>
  
  <p>I preallocated memory for res in both. And surprisingly, I found option 2 to be faster.</p>
  
  <p>Can someone explain how this is so?</p>
  
  <p>edit:
  I tried</p>
  
  <pre><code>K=10000;
  clear t1 t2
  t1=zeros(K,1);
  t2=zeros(K,1);
  
  for k=1:K
      clear res
      x = rand(100,100);
      a = rand(100,100);
      tic
      res = x*a;
      t1(k) = toc;
  end
  
  for k=1:K
      clear res2
      res2 = zeros(100,100);
      x = rand(100,100);
      a = rand(100,100);
      tic
      for i = 1:100
          res2(:,i) = x*a(:,i);
      end
      t2(k) = toc;
  end
  </code></pre>