title: Methods to speed up for loop in MATLAB
body: <p>I have just profiled my MATLAB code and there is a bottle-neck in this for loop:</p>
  
  <pre><code>for vert=-down:up
      for horz=-lhs:rhs
          y = y + x(k+vert.*length+horz).*DM(abs(vert).*nu+abs(horz)+1);
      end
  end
  </code></pre>
  
  <p>where y, x and DM are vectors I have already defined. I vectorised the loop by writing, </p>
  
  <pre><code>B=(-down:up)'*ones(1,lhs+rhs+1);
  C=ones(up+down+1,1)*(-lhs:rhs);
  y = sum(sum(x(k+length.*B+C).*DM(abs(B).*nu+abs(C)+1)));
  </code></pre>
  
  <p>But this ended up being sufficiently slower. </p>
  
  <p>Are there any suggestions on how I can speed up this for loop?</p>
  
  <p>Thanks in advance.</p>