简体   繁体   中英

How to get a matrix with polynomial factors from a vector with numpy?

Given a vector X = [x_0, x_1,...,x_N] and a given order p I want to get a matrix phi , which looks as follows:

在此处输入图像描述

I know how I could fill this matrix manually, but I was wondering, if there is already a function in numpy which does this?

This is already implemented by np.vander :

import numpy as np

x=range(1,6)
p=4
np.vander(x, p+1, increasing=True)
array([[  1,   1,   1,   1,   1],
       [  1,   2,   4,   8,  16],
       [  1,   3,   9,  27,  81],
       [  1,   4,  16,  64, 256],
       [  1,   5,  25, 125, 625]])

You could use nested list comprehensions:

import numpy as np

# example data
X = [1, 2, 3, 4]
p = 2

Phi = np.matrix([[X[i] ** j for j in range(p+1)] for i in range(len(X))])
Phi
matrix([[ 1,  1,  1],
        [ 1,  2,  4],
        [ 1,  3,  9],
        [ 1,  4, 16]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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