title: 2D Discrete Cosine Transform using 1D DCT
body: <p>I am trying to implement the 2D Discrete Cosine Transform to an image by using 
  1D DCT operations. My output is incorrect if I compare it to the <code>dct2</code> MATLAB function. I don't understand what went wrong in my code and where it's happening.</p>
  
  <p>If someone can point out the mistake or any other advice, that would be really helpful.</p>
  
  <p>Here is my code written in MATLAB</p>
  
  <pre><code>% main function
  signal=rand(100);
  signal_dct=myDCT(signal);
  figure; imshow((signal_dct));
  
  % function to calculate 2D DCT of an image
  function res=myDCT(signal)
  
      signal=double(signal);
  
      l=size(signal,1);
  
      res=zeros(l);  %initialize the final result matrix
  
      for k=1:l     %calculate 1D DCT of each row of image
          res(k,:)=mdct(signal(k,:));  
      end
  
      for k=1:l   %calculate 1D DCT of each column of image
          res(:,k)=mdct(res(:,k));
      end
  end
  
  %% function to calculate 1D DFT of a 1D signal
  function res=mdct(signal)
  
      l=size(signal,1);
  
      for i=1:l
  
          if i==1   %for signal index of 1, alpha is 1/sqrt(l)
              alpha=sqrt(1/l);
          else   %for signal index of greater than 1
              alpha=sqrt(2/l);
          end
  
          j=[1:l];
          % summation calculates single entry of res by applying the  
          % formula of DCT on the signal
          summation=sum(sum(signal(j)*cos((pi*(2*(j-1)+1)*(i-1))/(2*l))));
          res(i)=alpha*summation;        
      end
  end
  </code></pre>