title: Calculate gradients of a 3d structure in Matlab
body: <p>I try to use the Matlab function <code>gradient</code> to calculate the gradient of a volume. I use <code>quiver</code> to display the gradients of slices.</p>
  
  <p>I use a cube-like volume, which is symmetric with respect to x, y, and z axis. To my surprise, the result is not the same for all slices. Actually only the result in the xy-plane (Z-slice, last image) is the expected result.</p>
  
  <p>I know that there are issues when calculating the gradient at the border of an image. But for me the result at the border is not important and so I don't care if the result next to the border is correct. For me it would be important that all three images look like the last one.</p>
  
  <p>Can somebody tell me what is wrong with my code? Thanks!</p>
  
  <p><img src="https://i.stack.imgur.com/TrVFb.png" alt="gradients of slice in yz-plane">
  <img src="https://i.stack.imgur.com/2o5A9.png" alt="gradients of slice in xz-plane">
  <img src="https://i.stack.imgur.com/CoFuF.png" alt="gradients of slice in xy-plane"></p>
  
  <pre><code>f=zeros(20,20,20);
  space = 5;
  f(:,:,space) = 1; f(:,:,end-space) = 1;
  f(:,space,:) = 1; f(:,end-space,:) = 1;
  f(space,:,:) = 1; f(end-space,:,:) = 1;
  space = 4;
  f(:,:,space) = 1; f(:,:,end-space) = 1;
  f(:,space,:) = 1; f(:,end-space,:) = 1;
  f(space,:,:) = 1; f(end-space,:,:) = 1;
  
  size_iso = size(f);
  x_slice = round(size_iso(1)/2);
  y_slice = round(size_iso(2)/2);
  z_slice = round(size_iso(3)/2);
  
  % display the gradient of the edge map
  [fx,fy,fz] = gradient(f,0.1); 
  figure;
  image(squeeze(f(x_slice,:,:))*50); colormap(gray(64)); hold on;
  quiver(squeeze(fy(x_slice,:,:)),squeeze(fz(x_slice,:,:))); 
  axis equal;
  title(['edge map gradient of X-slice ', num2str(x_slice)]);
  
  figure;
  image(squeeze(f(:,y_slice,:))*50); colormap(gray(64)); hold on;
  quiver(squeeze(fx(:,y_slice,:)),squeeze(fz(:,y_slice,:))); 
  axis equal;
  title(['edge map gradient of Y-slice ', num2str(y_slice)]);
  
  figure;
  image(squeeze(f(:,:,z_slice))*50); colormap(gray(64)); hold on;
  quiver(squeeze(fx(:,:,z_slice)),squeeze(fy(:,:,z_slice))); 
  axis equal;
  title(['edge map gradient of Z-slice ', num2str(z_slice)]);
  </code></pre>