如何将矩阵提升为按升序增加的数组中元素的幂?

How to raise a matrix to the power of elements in an array that is increasing in an ascending order?

目前我有一个由以下方法生成的 C 矩阵:

def c_matrix(n):
    exp = np.exp(1j*np.pi/n)
    exp_n = np.array([[exp, 0], [0, exp.conj()]], dtype=complex)
    c_matrix = np.array([exp_n**i for i in range(1, n, 1)], dtype=complex)
    return c_matrix

这基本上是使用列表理解生成从 0 到 n-1 的数字列表,然后 returns 矩阵列表 exp_n 被提升为递增的元素列表。即

exp_n**[0, 1, ..., n-1] = [exp_n**0, exp_n**1, ..., exp_n**(n-1)]

所以我想知道是否有更 numpythonic 的方式来做到这一点(为了利用 Numpy 的广播能力),比如:

exp_n**np.arange(1,n,1) = np.array(exp_n**0, exp_n**1, ..., exp_n**(n-1))

你说的是范德蒙矩阵。 Numpy 有 numpy.vander


def c_matrix_vander(n):
    exp = np.exp(1j*np.pi/n)
    exp_n = np.array([[exp, 0], [0, exp.conj()]], dtype=complex)
    return np.vander(exp_n.ravel(), n, increasing=True)[:, 1:].swapaxes(0, 1).reshape(n-1, 2, 2)

性能

In [184]: %timeit c_matrix_vander(10_000)
849 µs ± 14.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [185]: %timeit c_matrix(10_000)
41.5 ms ± 549 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

验证

>>> np.isclose(c_matrix(10_000), c_matrix_vander(10_000)).all()
True