Reputation: 59
I have a matrix A and matrix b
A = [[536.08008658 1. ]
[580.40909091 1. ]
[624.73809524 1. ]
[671.83766234 1. ]
[718.93722944 1. ]
[760.495671 1. ]
[810.36580087 1. ]
[857.46536797 1. ]]
b = [[210.82467532]
[188.66017316]
[172.03679654]
[166.495671 ]
[169.26623377]
[177.57792208]
[196.97186147]
[224.67748918]]
How do i find matrix x which is a 2 x 1 matrix?
I tried lsq = np.linalg.solve(A, b)
but I had this error:
---------------------------------------------------------------------------
LinAlgError Traceback (most recent call last)
<ipython-input-18-e0f5641243e6> in <module>
17
18 # a, b = np.linalg.lstsq(A, y, rcond=None)[0]
---> 19 lsq = np.linalg.solve(A, y)
20 print(lsq)
21
<__array_function__ internals> in solve(*args, **kwargs)
~/opt/anaconda3/lib/python3.8/site-packages/numpy/linalg/linalg.py in solve(a, b)
379 a, _ = _makearray(a)
380 _assert_stacked_2d(a)
--> 381 _assert_stacked_square(a)
382 b, wrap = _makearray(b)
383 t, result_t = _commonType(a, b)
~/opt/anaconda3/lib/python3.8/site-packages/numpy/linalg/linalg.py in _assert_stacked_square(*arrays)
202 m, n = a.shape[-2:]
203 if m != n:
--> 204 raise LinAlgError('Last 2 dimensions of the array must be square')
205
206 def _assert_finite(*arrays):
LinAlgError: Last 2 dimensions of the array must be square
Any thoughts as to how to solve this with that specific method would be helpful. Thanks.
Upvotes: 0
Views: 2132
Reputation: 4431
If you absolutely have to use np.linalg.solve then you can do so as below. However it would be better (faster, less inaccurate to use a specialised least squares routine
(Sorry its not python, but I don't know python) This is the 'normal equations' approach
C = A'*A and z = A'*y (here A' is the transpose of A)
solve C*x = z for x
Upvotes: 0
Reputation: 1489
You are calling the wrong function for that job. That is solving a normal Linear System which requires the same number of equations as variables (i.e. it must be square). What you are looking for is numpy.linalg.lstsq
which returns the least-squares solution to a linear matrix equation.
import numpy as np
A = [[536.08008658, 1. ],
[580.40909091, 1. ],
[624.73809524, 1. ],
[671.83766234, 1. ],
[718.93722944, 1. ],
[760.495671 , 1. ],
[810.36580087, 1. ],
[857.46536797, 1. ]]
b = [[210.82467532],
[188.66017316],
[172.03679654],
[166.495671 ],
[169.26623377],
[177.57792208],
[196.97186147],
[224.67748918]]
lsq = np.linalg.lstsq(A, b, rcond=None)
print(lsq)
Upvotes: 2