title: Image rotation by Matlab without using imrotate
body: <p>I am trying to rotate an image with Matlab without using imrotate function. I actually made it by using transformation matrix.But it is not good enough.The problem is, the rotated image is "sliding".Let me tell you with pictures.</p>
  
  <p>This is my image which I want to rotate:</p>
  
  <p><img src="https://i.stack.imgur.com/viXyK.png" alt="enter image description here"></p>
  
  <p>But when I rotate it ,for example 45 degrees, it becomes this:</p>
  
  <p><img src="https://i.stack.imgur.com/q7YsX.png" alt="enter image description here"></p>
  
  <p>I am asking why this is happening.Here is my code,is there any mathematical or programming mistakes about it?</p>
  
  <pre><code>image=torso;
  
  %image padding
  [Rows, Cols] = size(image); 
  Diagonal = sqrt(Rows^2 + Cols^2); 
  RowPad = ceil(Diagonal - Rows) + 2;
  ColPad = ceil(Diagonal - Cols) + 2;
  imagepad = zeros(Rows+RowPad, Cols+ColPad);
  imagepad(ceil(RowPad/2):(ceil(RowPad/2)+Rows-1),ceil(ColPad/2):(ceil(ColPad/2)+Cols-1)) = image;
  
  degree=45;
  
  %midpoints
  midx=ceil((size(imagepad,1)+1)/2);
  midy=ceil((size(imagepad,2)+1)/2);
  
  imagerot=zeros(size(imagepad));
  
  %rotation
  for i=1:size(imagepad,1)
      for j=1:size(imagepad,2)
  
           x=(i-midx)*cos(degree)-(j-midy)*sin(degree);
           y=(i-midx)*sin(degree)+(j-midy)*cos(degree);
           x=round(x)+midx;
           y=round(y)+midy;
  
           if (x&gt;=1 &amp;&amp; y&gt;=1)
                imagerot(x,y)=imagepad(i,j); % k degrees rotated image         
           end
  
      end
  end
  
   figure,imagesc(imagerot);
   colormap(gray(256));
  </code></pre>