简体   繁体   English

将 1 xn 数组提升到 mx 1 数组中的所有幂到 Python 中的 mxn 数组

[英]Raise 1 x n array to all powers in m x 1 array to m x n array in Python

Given 2 1d arrays of any length I wish to raise each value in the 'base' array to each power in the 'exponent' array to produce a 2d array/matrix.给定 2 个任意长度的一维数组,我希望将“基”数组中的每个值提高到“指数”数组中的每个幂以生成二维数组/矩阵。

a = [a0, a1, a2, ... , an]
b = [b0, b1, b2, ... , bm]

desired output:所需的输出:

[a0^b0, a1^b0, ... , an^b0 ; 
 a0^b1, a1^b1, ... , an^b1 ;
 ...
 a0^bm, a1^bm, ... , an^bm ]

I am coming from a Matlab background where this can very easily be done for a column and row vector:我来自 Matlab 背景,可以很容易地为列和行向量完成此操作:

a.^b

as described here: https://www.mathworks.com/help/matlab/ref/power.html#mw_0a0fb331-989a-442b-ba2c-ede92a343828如此处所述: https : //www.mathworks.com/help/matlab/ref/power.html#mw_0a0fb331-989a-442b-ba2c-ede92a343828

However in Python with numpy or scipy etc I cant find any easy way to do this.但是在带有 numpy 或 scipy 等的 Python 中,我找不到任何简单的方法来做到这一点。 I have to assume there is a fairly optimized way to do this simply (with no list comprehension), given how intuitive and easy it is in Matlab.我必须假设有一种相当优化的方法可以简单地做到这一点(没有列表理解),因为它在 Matlab 中是多么的直观和容易。

In Python the symbol used to indicate exponentiation is ** , and numpy supports vectorized exponentiation of equal-length arrays just fine:在 Python 中,用于表示求幂的符号是** ,并且 numpy 支持等长数组的向量化求幂就好了:

>>> a = np.array([1, 2, 3, 4, 5])
>>> b = np.array([5, 4, 3, 2, 1])
>>> a**b
array([ 1, 16, 27, 16,  5])

If you want your desired result however you must exponentiate a row vector with a column vector:如果你想要你想要的结果,你必须用列向量对行向量取幂:

>>> a = np.array([[1, 2, 3, 4, 5]]) # Notice now a 2D array, a horizontal vector.
>>> b = np.array([[5, 4, 3, 2, 1]])
>>> a
array([[1, 2, 3, 4, 5]])
>>> b.T
array([[5],
       [4],
       [3],
       [2],
       [1]])
>>> a**b.T
array([[   1,   32,  243, 1024, 3125],
       [   1,   16,   81,  256,  625],
       [   1,    8,   27,   64,  125],
       [   1,    4,    9,   16,   25],
       [   1,    2,    3,    4,    5]])

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

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