1

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.

Jdip
  • 5,980
  • 3
  • 7
  • 29
Jailer
  • 13
  • 3
  • 1
    What do you get when you compute the ratio $X/\texttt{dct}(x)$ ? – Jdip Jan 29 '23 at 08:20
  • 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 – Jailer Jan 29 '23 at 09:06
  • Ok now try another example and look at the ratio again. You have a scaling issue that’s all. Btw, $0\cdot 4=0$ – Jdip Jan 29 '23 at 22:18

1 Answers1

2

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$

Jdip
  • 5,980
  • 3
  • 7
  • 29