1 ## Copyright (C) 2001 Paul Kienzle <pkienzle@users.sf.net>
3 ## This program is free software; you can redistribute it and/or modify it under
4 ## the terms of the GNU General Public License as published by the Free Software
5 ## Foundation; either version 3 of the License, or (at your option) any later
8 ## This program is distributed in the hope that it will be useful, but WITHOUT
9 ## ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10 ## FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
13 ## You should have received a copy of the GNU General Public License along with
14 ## this program; if not, see <http://www.gnu.org/licenses/>.
17 ## Computes the discrete cosine transform of x. If n is given, then
18 ## x is padded or trimmed to length n before computing the transform.
19 ## If x is a matrix, compute the transform along the columns of the
20 ## the matrix. The transform is faster if x is real-valued and even
23 ## The discrete cosine transform X of x can be defined as follows:
26 ## X[k] = w(k) sum x[n] cos (pi (2n+1) k / 2N ), k = 0, ..., N-1
29 ## with w(0) = sqrt(1/N) and w(k) = sqrt(2/N), k = 1, ..., N-1. There
30 ## are other definitions with different scaling of X[k], but this form
31 ## is common in image processing.
33 ## See also: idct, dct2, idct2, dctmtx
35 ## From Discrete Cosine Transform notes by Brian Evans at UT Austin,
36 ## http://www.ece.utexas.edu/~bevans/courses/ee381k/lectures/09_DCT/lecture9/
37 ## the discrete cosine transform of x at k is as follows:
40 ## X[k] = sum 2 x[n] cos (pi (2n+1) k / 2N )
43 ## which can be computed using:
45 ## y = [ x ; flipud (x) ]
47 ## X = exp( -j pi [0:N-1] / 2N ) .* Y
49 ## or for real, even length x
51 ## y = [ even(x) ; flipud(odd(x)) ]
53 ## X = 2 real { exp( -j pi [0:N-1] / 2N ) .* Y }
55 ## Scaling the result by w(k)/2 will give us the desired output.
57 function y = dct (x, n)
59 if (nargin < 1 || nargin > 2)
64 transpose = (rows (x) == 1);
66 if transpose, x = x (:); endif
71 x = [ x ; zeros(n-nr,nc) ];
73 x (nr-n+1 : n, :) = [];
79 w = [ sqrt(1/4/n); sqrt(1/2/n)*exp((-1i*pi/2/n)*[1:n-1]') ] * ones (1, nc);
81 if ( realx && rem (n, 2) == 0 )
82 y = fft ([ x(1:2:n,:) ; x(n:-2:1,:) ]);
83 y = 2 * real( w .* y );
85 y = fft ([ x ; flipud(x) ]);
87 if (realx) y = real (y); endif
89 if transpose, y = y.'; endif