Reputation: 330
I have a data set, and I'm trying to get the equation of a plane from it. That is: a*x + b*y + c = z In my case, dT = x, dTa = y, Constant = c, and dV = z.
I'm able to do this quite easily in Matlab, code:
dT = [8.5; 3.5; .4; 12.9]
dT =
8.5000
3.5000
0.4000
12.9000
dTa = [8.5; 18; 22; 34.9]
dTa =
8.5000
18.0000
22.0000
34.9000
dV = [3; 1; .5; 3]
dV =
3.0000
1.0000
0.5000
3.0000
Constant = ones(size(dT))
Constant =
1
1
1
1
coefficients = [dT dTa Constant]\dV
coefficients =
0.2535
-0.0392
1.0895
so, here, coefficients = (a, b, c).
Is there an equivalent way to do this in Python? I've been trying to use the numpy module (numpy.linalg), but its not working out so well. For one, the matrix MUST be square, and even so, it doesn't give very nice answers. For example:
Error:
>>> dT
[8.5, 3.5, 0.4, 12.9]
>>> dTa
[8.5, 18, 22, 34.9]
>>> dV
[3, 1, 0.5, 3]
>>> Constant
array([ 1., 1., 1., 1.])
>>> numpy.linalg.solve([dT, dTa, Constant], dV)
Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
numpy.linalg.solve([dT, dTa, Constant], dV)
File "C:\Python27\lib\site-packages\numpy\linalg\linalg.py", line 312, in solve
_assertSquareness(a)
File "C:\Python27\lib\site-packages\numpy\linalg\linalg.py", line 160, in _assertSquareness
raise LinAlgError, 'Array must be square'
LinAlgError: Array must be square
Wokrking with square matrix:
>>> dT
array([ 8.5, 3.5, 12.9])
>>> dTa
array([ 8.5, 18. , 34.9])
>>> dV
array([3, 1, 3])
>>> Constant
array([ 1., 1., 1.])
>>> numpy.linalg.solve([dT, dTa, Constant], dV)
array([ 2.1372267 , 2.79746835, -1.93469505])
These are not even close to the values I got before!!
Any ideas guys? Any advice appreciated.
Upvotes: 0
Views: 1177
Reputation: 330
So, I found this picture
and adapted it to include a constant. Here's my solved code:
X = 0
XX = 0
XY = 0
XZ = 0
Y = 0
YY = 0
YZ = 0
Z = 0
for j in range(0, len(dTemp)):
X = X + dTemp[j]
XX = XX + (dTemp[j] * dTemp[j])
XY = XY + (dTemp[j] * dTempA[j])
XZ = XZ + (dTemp[j] * Applied[j])
Y = Y + dTempA[j]
YY = YY + (dTempA[j] * dTempA[j])
YZ = YZ + (dTempA[j] * Applied[j])
Z = Z + Applied[j]
lhs = numpy.array([[XX, XY, X], [XY, YY, Y], [X, Y, 1]])
rhs = numpy.array([XZ, YZ, Z])
coefficients = numpy.linalg (lhs, rhs)
a = coefficients[0]
b = coefficients[1]
c = coefficients[2]
I think that did the trick! still, values a little off, but maybe that's because Matlab was using a different algorithm?
Upvotes: 0
Reputation: 11
In the first example, you need to use numpy.linalg.lstsq
. Either way, you appear to have mixed up the rows and columns of your matrix. Fix it using something like numpy.linalg.solve(zip(dT, dTa, Constant), dV)
.
Upvotes: 1