2

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?

Community
  • 1
  • 1
Kid Charlamagne
  • 558
  • 1
  • 10
  • 27

1 Answers1

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,).

Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
  • Sorry. Yes it is a typo for `A`. – Kid Charlamagne Feb 06 '17 at 06:48
  • How do I transform the output of the function `foo` to the shape `(3,)`? – Kid Charlamagne Feb 06 '17 at 06:51
  • 1
    Doesn't using `np.array` for `b` work? And I'm pretty sure you don't need the `.tolist()`. – Paul Panzer Feb 06 '17 at 06:57
  • No you still get the same error unfortunately. I tried transposing the matrices. But Still doesn't work. I used `b = np.array([2,1,1])` – Kid Charlamagne Feb 06 '17 at 07:28
  • Strange, works fpr me. Is your posted code identical to the one you're actually using? I'm asking because if for example you were using an `np.matrix` for `A` instead of a list of lists it wouldn't work. – Paul Panzer Feb 06 '17 at 07:35
  • You are right it works. I tried this on a new jupyternotebook and it works. I think some function got overwriten with something I had declared earlier. I wonder if this has been happening every time. Thanks for the help. – Kid Charlamagne Feb 06 '17 at 07:40