左矩阵除法和Numpy解决 [英] Left Matrix Division and Numpy Solve

查看:41
本文介绍了左矩阵除法和Numpy解决的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将包含\运算符的代码从Matlab(八度)转换为Python.示例代码

I am trying to convert code that contains the \ operator from Matlab (Octave) to Python. Sample code

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

这有效并产生1.2作为答案.使用此网页

This works and produces 1.2 as an answer. Using this web page

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 的非方阵?

How come Matlab \ works with non square matrix for B?

有什么解决办法吗?

推荐答案

来自 MathWorks文档进行左矩阵除法

如果A是m〜= n的n×n矩阵,而B是m的列向量组件或具有多个此类列的矩阵,则X = A \ B为最小二乘解对欠定或过度确定换句话说,X将范数(A * X-B)最小化,向量AX的长度-B.

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 :

The equivalent in numpy is 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]])

这篇关于左矩阵除法和Numpy解决的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆