title: Fast computation of a gradient of an image in matlab
body: <p>I was trying to optimize my code and found that one of my code is a bottleneck. My code was :</p>
  
  <pre><code>function [] = one(x)
  I = imread('coins.png');
  I = double(I);
  I = imresize(I,[x x]);
  sig=.8;    % scale parameter in Gaussian kernel
  G=fspecial('gaussian',15,sig); % Caussian kernel
  Img_smooth=conv2(I,G,'same');  % smooth image by Gaussiin convolution
  [Ix,Iy]=gradient(Img_smooth);
  f=Ix.^2+Iy.^2;
  g=1./(1+f);  % edge indicator function.
  end
  </code></pre>
  
  <p>I tried to run it like this : 
  clear all;close all;</p>
  
  <pre><code>x=4000;N=1;
  tic
  for i=1:N
      one(x);
  end
  toc
  </code></pre>
  
  <p>I found that the largest amount of time was consumed by the <strong>gradient operator</strong> statement(about 60%) of the total time. So it got me thinking how can I optimize my code further ....</p>
  
  <p>I consulted few sites like : <a href="http://www.mathworks.in/matlabcentral/fileexchange/29887-dgradient">Dgradient</a> and <a href="http://regularize.wordpress.com/2013/06/19/how-fast-can-you-calculate-the-gradient-of-an-image-in-matlab/">http://regularize.wordpress.com/2013/06/19/how-fast-can-you-calculate-the-gradient-of-an-image-in-matlab/</a></p>
  
  <p>However Dgradient is a MEX file and I do not want to use it. I wanted to write my own gradient function. I read in the blogs that the gradient operator in matlab is significantly slower and be speeded up by using shift &amp; substract and sparse matrix. </p>
  
  <p>I do not have knowledge about sparse matrix. However I did try doing it by using shift and substract method. However <strong>I am preety sure my code is wrong</strong>. Please could anyone clarify what kind of difference matlab uses for calculation of its gradient ? And show me how to do it in my code ?</p>
  
  <pre><code>clc;clear all;close all;
  I = imread('coins.png');
  I = double(I(:,:,1));
  I = imresize(I,[4 4]);
  
  tic
  [dx dy] = gradient(I);
  toc
  
  tic
  %//Doing forward difference on both directions
  dx1 = [I(:,2:end) I(:,end)] - I;
  dy1 = [I(2:end,:);I(end,:)] - I;
  toc
  </code></pre>
  
  <p>Please could you guys look into the code and suggest me how to correctly apply it ? Or guide me how to do so using sparse matrix ?</p>