Uri Greenberg
Uri Greenberg

Reputation: 252

Implementing DCT from its connection to DFT via FFT in Matlab

I've got this assignment to implement a 1D DCT-II myself in Matlab where the 1D DCT-II of an even length sequence is defined as: enter image description here

Naturally, using the built-in dct function is prohibited whilethe fft functions are available to me. Using the relation between DCT-II and DFT I've computed the DCT coefficients from the DFT coefficients of the even and symmetric extension of the original sequence as follows: enter image description here

However, my own implementation doesn't agree with the build-in dct function. I've seen a couple of questions about implementation of DCT but was unable to find the problem in my own code. My code follows.

function X_dct = dct_new (x_sig)
N = length(x_sig);
if mod(N,2) ~= 0
    error('Sequence is of odd length.');
end

x_hat = zeros(N, 1);
for n = 1: (N/2)
    x_hat(n) = x_sig((2*n)-1);
    x_hat(N-n+1) = x_sig(2*n);
end

X_hat_dft = fftshift(fft(x_hat));
X_dct = zeros(1, N);
for k = 1:N
    X_dct(k) = real(alpha(k-1,N)* exp(-1i*pi*(k-1)/(2*N))*(X_hat_dft(k)));
end
end

function a = alpha(k, N)
    if k == 0
        a = sqrt(1/N);
    else
        a = sqrt(2/N);
    end
end

Thanks in advance.

Upvotes: 1

Views: 1171

Answers (1)

Uri Greenberg
Uri Greenberg

Reputation: 252

As pointed out by Cris Luengo in his comment my mistake was the usage of fftshift before computing the dct coefficients as I didn't take the shift position.

Upvotes: 1

Related Questions