从元组到具有numpy的线性方程

时间:2016-06-29 18:56:43

标签: python numpy matrix interpolation linear-algebra

我在以下主题中需要帮助。假设我有三个点,每个点都有x,y坐标和相应的z值,例如:

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

稍后,我想找到倾角方向和插值平面的倾角。我想到了一个线性方程组和矩阵如下:

enter image description here

假设我可以将其写为Ba=z,其中B是我的矩阵,其中包含x,y值和z带有z值的矢量。

稍后,我想通过以下方式解决这个问题:

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

我的问题是:如何用我的元素提取矩阵,x和y值以及带有我元组中z值的向量?我现在太困了。

3 个答案:

答案 0 :(得分:1)

您可以使用

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]

例如,

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

我会使用像这样的列表连接

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

一个例子

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