2011-08-23 84 views
11

我想將包含\ operator的代碼從Matlab(Octave)轉換爲Python。示例代碼左矩陣分區和Numpy求解

B = [2;4] 
b = [4;4] 
B \ b 

此工作併產生1.2作爲答案。使用本網頁

http://mathesaurus.sourceforge.net/matlab-numpy.html

我翻譯,作爲:

import numpy as np 
import numpy.linalg as lin 
B = np.array([[2],[4]]) 
b = np.array([[4],[4]]) 
print lin.solve(B,b) 

這給了我一個錯誤:

numpy.linalg.linalg.LinAlgError: Array must be square 

怎麼來的Matlab的\工作與乙類非方陣?

任何解決方案?

回答

14

MathWorks documentation左矩陣劃分:

If A is an m-by-n matrix with m ~= n and B is a column vector with m components, or a matrix with several such columns, then X = A\B is the solution in the least squares sense to the under- or overdetermined system of equations AX = B. In other words, X minimizes norm(A*X - B), the length of the vector AX - B.

在numpy的等效是np.linalg.lstsq

In [15]: B = np.array([[2],[4]]) 

In [16]: b = np.array([[4],[4]]) 

In [18]: x,resid,rank,s = np.linalg.lstsq(B,b) 

In [19]: x 
Out[19]: array([[ 1.2]]) 
8

Matlab的,實際上做了一些不同的操作時使用\操作,取決於涉及的矩陣的形狀(更多細節見here)。在你的例子中,Matlab正在返回一個最小二乘解,而不是像直角矩陣那樣直接求解線性方程。要獲得numpy的相同的行爲,這樣做:

import numpy as np 
import numpy.linalg as lin 
B = np.array([[2],[4]]) 
b = np.array([[4],[4]]) 
print np.linalg.lstsq(B,b)[0] 

這應該給你相同的解決方案Matlab的。

1

可以形成左逆:

import numpy as np 
import numpy.linalg as lin 
B = np.array([[2],[4]]) 
b = np.array([[4],[4]]) 

B_linv = lin.solve(B.T.dot(B), B.T) 
c = B_linv.dot(b) 
print('c\n', c) 

結果:

c 
[[ 1.2]] 

其實,我們可以簡單地運行解算一次,而不會形成反,像這樣:

c = lin.solve(B.T.dot(B), B.T.dot(b)) 
print('c\n', c) 

結果:

c 
[[ 1.2]] 

....像以前一樣

爲什麼?因爲:

我們:

enter image description here

乘以通過B.T,給了我們:

enter image description here

現在,B.T.dot(B)爲方形,滿秩,確實有逆。因此,我們可以乘以B.T.dot(B)的倒數,或使用求解器,如上所示,得到c