optimize.root with a matrix equation

跟風遠走 提交于 2021-01-27 19:30:22

问题


I am trying to solve the following linear system using optimize.root

AX = b

With the following code.

A = [[0,1,0],[2,1,0],[1,4,1]]

def foo(X):
   b = np.matrix([2,1,1])
   out = np.dot(A,X) - b
   return out.tolist()

sol = scipy.optimize.root(foo,[0,0,0])

I know that I can simply use the numpy.linalg.solve to do this easily. But I am actually trying to solve a non linear system that is in matrix form. See my question here. So I need to find a way to make this method work. To do that I am trying to solve this problem in this simple case. But I get the error

TypeError: fsolve: there is a mismatch between the input and output shape of the 'func' argument 'foo'.Shape should be (3,) but it is (1, 3).

From what I have read from other similar stackoverflow questions this happens because the out put of the foo function is not compatible with the shape of the initial guess [0,0,0]

Surely there is a way to solve this equation using scipy.optimize.root. Can anyone please help?


回答1:


(I'm assuming the capital B in your .dot is a typo for A.)

Try using np.array for b. np.matrix creates a "row vector", i.e. shape (1, 3) whereas your initial guess has shape (3,).



来源:https://stackoverflow.com/questions/42059584/optimize-root-with-a-matrix-equation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!