Alex
Alex

Reputation: 337

From tuples to linear equations with numpy

i need help in the following topic. Lets say i have three points, each with x, y coordinates and a corresponding z value, e.g.:

p_0 = (x_0, y_0, z_0) : coordinates of first point
p_1 = (x_1, y_1, z_1) : coordinates of second point
p_2 = (x_2, y_2, z_2) : coordinates of third point

Later on, i want to find the dip direction and the dip of an interpolated plane. Im thinking of a linear equation system and matrix as followed:

enter image description here

Say i can write this as Ba=z, where B is my matrix with ones, the x and y values and z the vector with my z values.

Later on, i want to solve this system by:

(a_0, a_1, a_2) = np.linalg.solve(B, z)

My problem is: how can i extract the matrix with my ones, the x and y values and the vector with my z values from my tuples? I am so stuck right now.

Upvotes: 2

Views: 498

Answers (3)

Chris Mueller
Chris Mueller

Reputation: 6680

I would use a list concatenation like so

>>> B = [[1, x[0], x[1]] for x in [p_0, p_1, p_2]]
>>> z = [[x[2]] for x in [p_0, p_1, p_2]]

An example

>>> p_0, p_1, p_2 = (1, 2, 3), (4, 5, 6), (7, 8, 9)
>>> B = [[1, x[0], x[1]] for x in [p_0, p_1, p_2]]
>>> z = [[x[2]] for x in [p_0, p_1, p_2]]
>>> print(B)
    [[1, 1, 2], [1, 4, 5], [1, 7, 8]]
>>> print(z)
    [[3], [6], [9]]

Upvotes: 1

percusse
percusse

Reputation: 3106

>>> p_0 = (-1,2,3)
>>> p_1 = (4,5,6)
>>> p_2 = (7,8,9)
>>> B = np.c[np.ones((3,1)),np.c_[p_0,p_1,p_2]]
>>> np.linalg.solve(B[:,:-1],B[:,-1])

Upvotes: 1

unutbu
unutbu

Reputation: 879759

You could use

p = np.row_stack([p_0, p_1, p_2])
B = np.ones_like(p)
# copy the first two columns of p into the last 2 columns of B
B[:, 1:] = p[:, :2]
z = p[:, 2]

For example,

import numpy as np

p_0 = (1,2,3)
p_1 = (4,-5,6)
p_2 = (7,8,9)

p = np.row_stack([p_0, p_1, p_2])
B = np.ones_like(p)
B[:, 1:] = p[:, :2]
z = p[:, 2]

a = np.linalg.solve(B, z)
print(a)
# [ 2.  1. -0.]

Upvotes: 1

Related Questions