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

2024-10-01 22:43:49 发布

您现在位置:Python中文网/ 问答频道 /正文

当我计算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()

Tags: importnumpymaindefasnprange矩阵
3条回答

你可以 print(c[::-1]) 这将颠倒c的顺序。 从How can I flip the order of a 1d numpy array?

只需从一开始将指数range换成另一种方式,之后就不必翻转:

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.]]

相关问题 更多 >

    热门问题