1
$\begingroup$

I'm trying to compute the Discrete Cosine Transform via FFT in C, using a response to this question, but the recommended solution gives me wrong results.

Function DCT in matlab:

x = [0:1:7]
x = 0     1     2     3     4     5     6     7

dct(x)
ans = 9.8995, -6.4423, 0, -0.6735, 0, -0.2009, 0, -0.0507

Type 2 DCT using 2N FFT mirrored (Makhoul):

x = [0, 1, 2, 3, 4,5, 6, 7, 7, 6, 5, 4, 3, 2, 1, 0]
X = fft(x)[:N]
X = X * exp(-1j*pi*k/(2*N))
(the real path) X = 56.0000, -25.7693, 0.0, -2.6938, 0.0, -0.8036, 0.0, -0.2028

The data are not even close to each other.

If anyone has an implementation of the DCT, I would be grateful if you could share it.

$\endgroup$
3
  • 1
    $\begingroup$ What do you get when you compute the ratio $X/\texttt{dct}(x)$ ? $\endgroup$
    – Jdip
    Commented Jan 29, 2023 at 8:20
  • $\begingroup$ If divide a vector by a vector: 5.1598 or [5.6569, 4.0000, 0, 4.0000, 0, 4.0000, 0, 4.0000] when element by element $\endgroup$
    – Jailer
    Commented Jan 29, 2023 at 9:06
  • $\begingroup$ Ok now try another example and look at the ratio again. You have a scaling issue that’s all. Btw, $0\cdot 4=0$ $\endgroup$
    – Jdip
    Commented Jan 29, 2023 at 22:18

1 Answer 1

2
$\begingroup$

Both of them are correct but there is a bit of difference in their gain.

Your implemented formula refers to:

enter image description here

but as you can see in Matlab help for DCT it calculates DCT by using the following formula:

enter image description here

It should be noted that you see $k-1$ instead of $k$ because the indexes in Matlab are $1$ to $k$

so there are the same but their ratio is $ \sqrt{2N} $ for $ k=2,3,...,N$ in Matlab or $ k=1,3,...,N-1$ in python and in $k=0$ the ratio is $2\sqrt{N}$ because in matlab the constant gain for the formula is $y(1)=\sqrt{1/N}$

So for your example which $N=8$ the ratio is $4$ for $k=1,2,3,...$ and $5.6569$ for $k=0$

$\endgroup$
1
  • $\begingroup$ +1 for a nice first answer, Mohammad! $\endgroup$
    – Jdip
    Commented Jan 31, 2023 at 15:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.