import cvxpy
def solve(A, B):
"""
Minimizes |AX - B|**2, assuming A and B are
square matrices for simplicity. If this optimized
error is zero, this corresponds to solving AX = B.
"""
n = A.shape[0]
X = cvxpy.Variable((n,n))
# Set objective
obj_fun = cvxpy.sum_squares(A*X - B)
objective = cvxpy.Minimize(obj_fun)
# Set constraints
constraints = [X >= 0]
prob = cvxpy.Problem(objective, constraints)
result = prob.solve(solver = "ECOS")
return X.value
一般来说,这在数学上是不可能的。给定}可逆的基本要求,
A
和{X
是唯一矩阵。如果您不喜欢X
所拥有的元素,那么您不能简单地要求另一个解决方案:没有解决方案。您必须更改A
或B
以获得不同的结果。在您可以使用
cvxpy
来解决它:编辑:我相信Prune的答案是正确的。您可以通过检查
results
来检查数值求解器中的错误是否为非零。在相关问题 更多 >
编程相关推荐