MENG
MENG

Reputation: 13

Use python fsolve for solving equations with 2-D input variables

By knowing that fsolve function can be easily applied using the following method:

import numpy as np
from scipy.optimize import fsolve
def solve(var):
    x = var[0]
    y = var[1]
    
    f = np.zeros(2)
    f[0] = x+y-a
    f[1] = 3*x+7*y-10
    return f
a = 2
var = fsolve(solve, np.zeros(2))
print(var)

BUT, how can I use fsolve function if a be a 2-D matrix like the following code (in comparison of the above code, just a has changed):

import numpy as np
from scipy.optimize import fsolve
def solve(var):
    x = var[0]
    y = var[1]
    
    f = np.zeros(2)
    f[0] = x+y-a
    f[1] = 3*x+7*y-10
    return f
a = np.array([[1,2], [3, 4]])
var = fsolve(solve, np.zeros(2))
print(var)

Edit:

What I want can be calculated using the following method. But is it possible to do it without using the for loops? (maybe if we define the var[0,:] and var[1,:] instead of var[0] and var[1], the problem would be solved)

import numpy as np
from scipy.optimize import fsolve
def solve(var):
    x = var[0]
    y = var[1]
    
    f = np.zeros(2)
    f[0] = x+y-a
    f[1] = 3*x+7*y-10
    return f
a1 = np.array([[1,2], [3,4]])
for a2 in a1:
    for a3 in a2:
        a=a3
        var = fsolve(solve, np.zeros(2))
        print(var)

Upvotes: 0

Views: 3890

Answers (1)

jomavera
jomavera

Reputation: 171

To avoid for loops, you can use numpy.vectorize:

def func(x,a):
  return [x[0]+x[1]-a, 3*x[0]+7*x[1]-10]
def solve(var, a):
  sol = fsolve(func, x0=var, args=(a))
  return sol

a = np.array([[1,2], [3,4]])
vfunc = np.vectorize(solve, excluded=['var'], otypes=[list])
sol = vfunc(var=np.zeros(2), a=a)

Upvotes: 0

Related Questions