title: how to optimize nested for loop in matlab
body: <p>I have a for loop nested thrice in a matlab program. Can any of you help me optimize it.</p>
  
  <pre><code>w=5;
  a = rand(m*n,10); b=rand(m,n);
  for i = 1 : m
     for j = 1 : n
        for k = 1 : l
           if (i-w &gt;= 1 &amp;&amp; i+w &lt;= m)
               featureL = a(((i-1)*n)+j,:); featureR = a(((i-1)*n)+j-d,:);
               D1(i,j,k) = sqrt( sum( (featureL - featureR) .* (featureL - featureR) ) );
               D2(i,j,k) = mean2( b(i-w:i+w, j-w:j+w) );
           end
        end
     end
  end
  </code></pre>
  
  <p>I know the performance could be heavily improved by using meshgrid, but I am not sure how to  do it.</p>
  
  <p>Thanks in anticipation.</p>
  
  <p>Can it be done something like this.. </p>
  
  <pre><code>[X Y Z] = meshgrid(1:m,1:n,1:l);
  D1(something containing X,Y,Z) = sqrt( sum( ( a(something cont. X,Y) - a(something cont. X,Y)).*(a(something cont. X,Y) - a(something cont. X,Y)) ) );
  % similarly D2
  </code></pre>
  
  <p>Thanks a lot!.</p>