Scipy:生成NxN个离散余弦矩阵

时间:2018-12-20 20:49:23

标签: python scipy dct

使用scipy,有没有一种简单的方法来仿真MATLAB的dctmtx函数的行为,该函数针对某些给定的N返回NxN DCT矩阵?有scipy.fftpack.dctn,但仅适用于DCT。 如果我不想使用scipy之外的其他依赖项,是否必须从头开始实现?

1 个答案:

答案 0 :(得分:1)

DCT是线性变换,因此获取变换矩阵的一种方法是将其应用于单位矩阵。在下面的示例中,我找到了长度为8的序列的矩阵(一般情况下将8更改为N):

In [124]: import numpy as np

In [125]: from scipy.fftpack import dct

In [126]: D = dct(np.eye(8), axis=0)

D是矩阵:

In [127]: D
Out[127]: 
array([[ 2.        ,  2.        ,  2.        ,  2.        ,  2.        ,  2.        ,  2.        ,  2.        ],
       [ 1.96157056,  1.66293922,  1.11114047,  0.39018064, -0.39018064, -1.11114047, -1.66293922, -1.96157056],
       [ 1.84775907,  0.76536686, -0.76536686, -1.84775907, -1.84775907, -0.76536686,  0.76536686,  1.84775907],
       [ 1.66293922, -0.39018064, -1.96157056, -1.11114047,  1.11114047,  1.96157056,  0.39018064, -1.66293922],
       [ 1.41421356, -1.41421356, -1.41421356,  1.41421356,  1.41421356, -1.41421356, -1.41421356,  1.41421356],
       [ 1.11114047, -1.96157056,  0.39018064,  1.66293922, -1.66293922, -0.39018064,  1.96157056, -1.11114047],
       [ 0.76536686, -1.84775907,  1.84775907, -0.76536686, -0.76536686,  1.84775907, -1.84775907,  0.76536686],
       [ 0.39018064, -1.11114047,  1.66293922, -1.96157056,  1.96157056, -1.66293922,  1.11114047, -0.39018064]])

验证D @ x等同于dct(x)

In [128]: x = np.array([1, 2, 0, -1, 3, 0, 1, -1])

In [129]: dct(x)
Out[129]: array([10.        ,  4.02535777, -1.39941754,  7.38025967, -1.41421356, -6.39104653, -7.07401092,  7.51550307])

In [130]: D @ x
Out[130]: array([10.        ,  4.02535777, -1.39941754,  7.38025967, -1.41421356, -6.39104653, -7.07401092,  7.51550307])

请注意,D @ x通常比dct(x)慢得多。