CIsForCookies
CIsForCookies

Reputation: 12837

Create a matrix using values from a tuple with numpy

I'm trying to create a matrix with values based on x,y values I have stored in a tuple. I use a loop to iterate over the tuple and perform a simple calculation on the data:

import numpy as np

# Trying to fit quadratic equation to the measured dots

N = 6
num_of_params = 3

# x values
x = (1,4,3,5,2,6)

# y values
y = (3.96, 24.96,14.15,39.8,7.07,59.4)

# X is a matrix N * 3 with the x values to the power of {0,1,2}
X = np.zeros((N,3))
Y = np.zeros((N,1))

print X,"\n\n",Y

for i in range(len(x)):
    for p in range(num_of_params):
        X[i][p] = x[i]**(num_of_params - p - 1)
    Y[i] = y[i]

print "\n\n"
print X,"\n\n",Y

Is this can be achieved in an easier way? I'm looking for some way to init the matrix like X = np.zeros((N,3), read_values_from = x)

Is it possible? Is there another simple way?

Python 2.7

Upvotes: 2

Views: 96

Answers (1)

Divakar
Divakar

Reputation: 221664

Extend array version of x to 2D with a singleton dim (dim with length=1) along the second one using np.newaxis/None. This lets us leverage NumPy broadcasting to get the 2D output in a vectorized manner. Similar philosophy for y.

Hence, the implementation would be -

X = np.asarray(x)[:,None]**(num_of_params - np.arange(num_of_params)  - 1)
Y = np.asarray(y)[:,None]

Or use the built-in outer method for np.power to get X that takes care of the array conversion under the hoods -

X = np.power.outer(x, num_of_params - np.arange(num_of_params)  - 1)

Alternatively, for Y, use np.expand_dims -

Y = np.expand_dims(y,1)

Upvotes: 2

Related Questions