Matlab to Python:使用 SVD 求解系统

Matlab to Python: Solving the system using SVD

我正在尝试将 Matlab 代码转换为 Python 代码。

我受困于

x = A\b;

其中 A 是二维数组 (2257x456) 并且 b 是一维数组 (2257x1).

Matlab输出的数组x是一维数组(456x1)

在 Matlab 代码中也有一条评论说:%Solve the system using SVD

那么我如何在 Python 中执行此操作?

我尝试使用以下代码,但没有成功。

x = np.linalg.lstsq(A,b)
x = np.linalg.lstsq(A.T, b.T)[1].T
x = A :\ b # found this [here][1]
x = np.linalg.solve(A,b)


[1]: https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html

更新:

产生的错误和结果:

x = np.linalg.solve(A,b) : LinAlgError: Last 2 dimensions of the array must be square

x = np.linalg.lstsq(A,b) : x is not expected result, it is 3D array (4x456x1)

x = np.linalg.lstsq(A.T, b.T)[1].T : LinAlgError: Incompatible dimensions

你想要np.linalg.lstsq(A,b)。再看一下 docstring,注意它有 returns 四个 值。所以要使用它,你会写

x, residuals, rank, s = np.linalg.lstsq(A,b)

或者,如果您想忽略除 x

之外的所有内容
x = np.linalg.lstsq(A,b)[0]