Python 在Numpy上反转输出矩阵值!有专门的命令吗?

Python 在Numpy上反转输出矩阵值!有专门的命令吗?,python,python-3.x,numpy,math,matrix,Python,Python 3.x,Numpy,Math,Matrix,当我计算Vandermonde时,我得到了正确的答案 这个矩阵的系数。然而,输出矩阵是相反的。 它应该是[6,-39,55,27],而不是[27,55,-39,6] 我的Vandermonde矩阵的输出被翻转,最终的解决方案 c、 他被打翻了 import numpy as np from numpy import linalg as LA x = np.array([[4],[2],[0],[-1]]) f = np.array([[7],[29],[27],[-73]]) def ma

当我计算Vandermonde时,我得到了正确的答案 这个矩阵的系数。然而,输出矩阵是相反的。 它应该是
[6,-39,55,27]
,而不是
[27,55,-39,6]

我的Vandermonde矩阵的输出被翻转,最终的解决方案 c、 他被打翻了

import numpy as np
from numpy import linalg as LA


x = np.array([[4],[2],[0],[-1]])
f = np.array([[7],[29],[27],[-73]])

def main():

    A_matrix = VandermondeMatrix(x)
    print(A_matrix)
    c = LA.solve(A_matrix,f) #coefficients of Vandermonde Polynomial
    print(c)

def VandermondeMatrix(x):
    n = len(x)
    A = np.zeros((n, n))
    exponent = np.array(range(0,n))
    for j in range(n):
        A[j, :] = x[j]**exponent
    return A





if __name__ == "__main__":
    main()
np.flip(c)

你可以这样做
打印(c[:-1])
这将颠倒c的顺序。 从

结果是一个(4,1)数组;使用以下命令反转行:

In [9]: _7[::-1]                                                                               
Out[9]: 
array([[  6.],
       [-39.],
       [ 55.],
       [ 27.]])
负跨步,
[::-1]
索引也用于反转Python列表和字符串

In [10]: ['a','b','c'][::-1]                                                                   
Out[10]: ['c', 'b', 'a']

只需从一开始将指数
设置为范围
的另一个方向,之后就不必翻转:

def VandermondeMatrix(x):
    n = len(x)
    A = np.zeros((n, n))
    exponent = np.array(range(n-1,-1,-1))
    for j in range(n):
        A[j, :] = x[j]**exponent
    return A
输出:


所以你的回答基本上和mkusz一样,但是有很多不必要的中间词results@LeoE,我测试了操作码,部分原因是我想知道为什么他得到了相反的答案。我看到他得到的是2d答案(而不是问题所暗示的1d),但你继续深入。在任何情况下,我的答案都是冗长的,旨在理解,而不仅仅是一个即时的解决方案。
exponent=np.arange(n)[::-1]
更短:)负跨步数组反转在任何情况下都不是一个昂贵的操作。我知道,但这是一个不必要的操作,所以如果你不必这么做,为什么要这么做呢?;)
def VandermondeMatrix(x):
    n = len(x)
    A = np.zeros((n, n))
    exponent = np.array(range(n-1,-1,-1))
    for j in range(n):
        A[j, :] = x[j]**exponent
    return A
#A_matrix:
[[64. 16.  4.  1.]
 [ 8.  4.  2.  1.]
 [ 0.  0.  0.  1.]
 [-1.  1. -1.  1.]]

#c:
[[  6.]
 [-39.]
 [ 55.]
 [ 27.]]