简体   繁体   English

如何将矩阵提高到数组中元素按升序递增的幂?

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

Currently I have a C matrix generated by: 目前,我有一个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

What this does is basically generate a list of number from 0 to n-1 using list comprehension, then returns a list of the matrix exp_n being raised to the elements of the ascendingly increasing list. 这样做基本上是使用列表exp_n生成一个从0到n-1的数字列表,然后将矩阵exp_n的列表返回到递增列表中的元素。 ie

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

So I was wondering if there's a more numpythonic way of doing it(in order to make use of Numpy's broadcasting ability) like: 所以我想知道是否还有更多的numpythonic方式(以便利用Numpy的广播功能),例如:

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

You're speaking of a Vandermonde matrix. 您说的是范德蒙矩阵。 Numpy has numpy.vander numpy.vandernumpy.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)

Performance 性能

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)

Validation 验证方式

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM