左矩阵除法和 Numpy 求解
我正在尝试将包含 \ 运算符的代码从 Matlab (Octave) 转换为 Python。示例代码
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 \ 如何与 B 的非方阵一起工作?
有什么解决办法吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自左矩阵除法的 MathWorks 文档:
。numpy 中的等效项是 np.linalg.lstsq:
From MathWorks documentation for left matrix division:
The equivalent in numpy is np.linalg.lstsq:
当使用 \ 运算符时,Matlab 实际上会执行许多不同的操作,具体取决于所涉及矩阵的形状(请参阅
这应该为您提供与 Matlab 相同的解决方案。
Matlab will actually do a number of different operations when the \ operator is used, depending on the shape of the matrices involved (see here for more details). In you example, Matlab is returning a least squares solution, rather than solving the linear equation directly, as would happen with a square matrix. To get the same behaviour in numpy, do this:
which should give you the same solution as Matlab.
您可以形成左逆:
结果:
实际上,我们可以简单地运行求解器一次,而不形成逆,如下所示:
结果:
...像以前一样
为什么?因为:
我们有:
乘以
BT
,得到:现在,
BTdot(B)
是正方形,满秩,确实有逆。因此,我们可以乘以BTdot(B)
的倒数,或者使用求解器(如上所述)来得到c
。You can form the left inverse:
Result:
Actually, we can simply run the solver once, without forming an inverse, like this:
Result:
.... as before
Why? Because:
We have:
Multiply through by
B.T
, gives us:Now,
B.T.dot(B)
is square, full rank, does have an inverse. And therefore we can multiply through by the inverse ofB.T.dot(B)
, or use a solver, as above, to getc
.