title: How can I make my code run faster?
body: <p>I'm currently working on a piece of code which blurs an image by taking a circular sample of pixels around each pixel, finding their mean and then applying that to the central pixel. It works, but it takes ages, especially with large images and large radii.</p>
  
  <p>Can anyone give me some tips on how to speed this up?</p>
  
  <pre><code>function [] = immean(IMAGE, r)
  
  %Find the maximum width, nx, and maximum height, ny, of the image - so that
  %it can be used to end the for-loop at the appropriate positions.
  
  [nx, ny] = size(IMAGE);
  
  %Create a completely black image of the same size as the subject image,
  %into which the appropriate pixel values can be fed.
  
  average = uint8(zeros(size(IMAGE)));
  
  %Loop through all the pixels of the image.
  
  for x = 1:nx
    for y = 1:ny
  
       %This next code takes a square sample of pixels, with dimensions of 
       %r x r.
       %First, set the boundaries of this square, from which the circular
       %sample of pixels will be taken.
  
       if x-r &lt;= 0
           startx = 1;
       else
           startx = x-r;
       end
  
       if x+r &gt; nx
           endx = nx;
       else
           endx = x+r;
       end
  
       if y-r &lt;= 0
           starty = 1;
       else
           starty = y-r;
       end
  
       if y+r &gt; ny
           endy = ny;
       else
           endy = y+r;
       end
  
       %Loop through this square sample and, if the pixel is within the
       %range of the circle, add its intensity to the total.
  
       total = 0;
       pixelcount = 0;
  
       for xp = startx : endx
  
         for yp = starty : endy  
  
               if (x-xp)^2 + (y-yp)^2 &lt;= r^2
                 total = total + uint32(IMAGE(xp, yp));
                 pixelcount = pixelcount + 1;
               end
         end
       end
  
       mean = total / pixelcount;
       average(x,y) = mean;
  
     end
  end
  
  imshow(average)
  </code></pre>
  
  <p>I've tried changing things like <code>uint32</code> but that hasn't worked. Beyond that, I'm a bit of a beginner, so I'm not sure what the best tricks are in this situation. Thanks for your time.</p>