Matlab question for implementing the discrete cosine transform and its inverse. Please provide all code.
Write GWO MATLAB functions called nydct and myidct that implement the discrete cosine transform (DCT) and its inverse for a vector of length N. Your code should be short (4 lines or less per function, no loops), efficient (it should make use of the fft command), and match the output of MATLAB's dct and idct commands. You can verify the latter with:
randn(1000000, 1); d1 = mydct(x); d2 = dct(x); norm(d1 - d2)
randn(1000000, 1); W1 = myidct(y); W2 = idct(y); norm(w1 - w2)
The norms of the differences should be small in both cases. The one thing you really have to handle here is the fact that the DCT uses cosines that are shifted by half a sample.
Useful observations:
- Use the variation of Euler's relation to write cos(t*n*k) as real{exp(-j*t*n*k)}.
- Write the DCT transform explicitly and use the fact that exp(-j*(2*pi/2*N)*k) = fft([n]). You can pad with zeros to get [n] to the right length.
- The iDCT is given by [n] = V# X[0] + V: X[N-1] + X[k] * cos((n + 1/2)*k). You can verify that for yourself by writing the DCT matrix, W, and using the fact that it's a unitary matrix (why) to compute W^-1 * W and verify that W^-1 * W * x = x.
If you choose to use ifft in the iDCT implementation, you can see this option in the commented line in the iDCT code.