Alen
Alen

Reputation: 133

Transforming vector to matrix

I have vector y with n values.

I want to create matrix that will have following form

y = [[1, y_1, y_1^2, ...,y_1^n], 
    [1, y_2, y_2^2, ...,y_2^n] ... [1, y_n, y_n^2, ...,y_n^n] ]

Upvotes: 0

Views: 49

Answers (2)

John Coleman
John Coleman

Reputation: 51998

A list comprehension is a natural way to proceed:

[[pow(yi,n) for n in range(1 + len(y))] for yi in y]

For y = [1,2,3,4] this produces

[[1, 1, 1, 1, 1],
[1, 2, 4, 8, 16],
[1, 3, 9, 27, 81],
[1, 4, 16, 64, 256]]

Upvotes: 1

adrtam
adrtam

Reputation: 7211

y = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
n = [0, 1, 2, 3, 4, 5]
matrix = [[yi**ni for ni in n] for yi in y]

Upvotes: 1

Related Questions