title: performance difference between subscript indexing and linear indexing
body: <p>I have a 2D matrix in MATLAB and I use two different ways to access its elements. One is based on subscript indexing and the other is based on linear indexing. I test both methods by following code:</p>
  
  <pre><code>N = 512; it = 400; im = zeros(N);
  %// linear indexing
  [ind_x,ind_y] = ndgrid(1:2:N,1:2:N);
  index = sub2ind(size(im),ind_x,ind_y);
  
  tic
  for i=1:it
      im(index) = im(index) + 1;
  end
  toc %//cost 0.45 seconds on my machine (MATLAB2015b, Thinkpad T410)
  
  %// subscript indexing
  x = 1:2:N;
  y = 1:2:N;
  
  tic
  for i=1:it
      im(x,y) = im(x,y) +1;
  end
  toc %// cost 0.12 seconds on my machine(MATLAB2015b, Thinkpad T410)
  
  %//someone pointed that double or uint32 might an issue, so we turn both into uint32
  
  %//uint32 for linear indexing
  index = uint32(index);
  tic
  for i=1:it
      im(index) = im(index) +1;
  end
  toc%// cost 0.25 seconds on my machine(MATLAB2015b, Thinkpad T410)
  
  %//uint32 for the subscript indexing
  x = uint32(1:2:N);
  y = uint32(1:2:N);
  tic
  for i=1:it
      im(x,y) = im(x,y) +1;
  end
  toc%// cost 0.11 seconds on my machine(MATLAB2015b, Thinkpad T410)
  
  %% /*********************comparison with others*****************/
  %//third way of indexing, loops
  tic
  for i=1:it
      for j=1:2:N
          for k=1:2:N
              im(j,k) = im(j,k)+1;
          end
      end
  end
  toc%// cost 0.74 seconds on my machine(MATLAB2015b, Thinkpad T410)
  </code></pre>
  
  <p>It seems that directly using subscript indexing is faster than the linear indexing obtained from <code>sub2ind</code>. Does anyone know why? I thought they were almost the same.</p>