discrete cosine transformation (dct-II) own implementation with loops I want to implement the DCT-2, the dctmtx:

$$X[k] = \sum_\limits{n=0}^{N-1} x[n] \,\cos \left(\frac{\pi}{N} \left(n+\tfrac12 \right)k \right) ~~~,~~ \;k=0,1, \dots N-1$$

function [ C ] = dct_mtx( N )
for k = 0:N-1
    for n = 0:N-1
       tmp(k+1,n+1) = cos((0.5+N)*k*pi/N);
    end
end

tmp(1,:) = tmp(1,:) / sqrt(2);
C = tmp;
end


If I call the function C = dct_mtx(3); and check the matrix C'*C = I and is not the identity but almost. 

What I have to change in the code to get the Identity in the end?

the identity looks like that:

1.50000000000000         -1.66533453693773e-16    -1.11022302462516e-16
-1.66533453693773e-16    1.50000000000000         -2.77555756156289e-16
-1.11022302462516e-16    -2.77555756156289e-16    1.50000000000000
You are missing a $\sqrt{\frac{2}{N}}$ scaling factor. Change the following line:

tmp(k+1,n+1) = sqrt(2/N)*cos((n+0.5)*k*pi/N);


You can also simply use Matlab's built-in function dctmtx.

C = dctmtx(n)