1

How can I turn

def square_error(f1,f2, u1,v1,sigu1,sigv1,rho1, u2,v2,sigu2,sigv2,rho2, u3,v3,sigu3,sigv3,rho3):

into:

def square_error(x):
#     x = [0.2,0.5,
#           1,1,1,1,0.3,
#           1,1,1,1,0.3,
#           1,1,1,1,0.3],
    f1,f2, u1,v1,sigu1,sigv1,rho1, u2,v2,sigu2,sigv2,rho2, u3,v3,sigu3,sigv3,rho3 = x

The scipy.minimize function only allow 1 argument for the target function, so I need to turn the variables into a single argument.

Cœur
  • 37,241
  • 25
  • 195
  • 267
ZK Zhao
  • 19,885
  • 47
  • 132
  • 206

1 Answers1

2

Yes you can do that, but you will have to the * syntax which will unpack the array into the parameters of the function.

For example:

def square_error( x,y,z ):
    print x,y,z

arr = [ 1, 2, 3 ]
square_error( *arr )

will unpack the values 1,2,3 into the parameters x,y,z


Or if you wanted to unpck the values into variables within the function, use sequence unpacking:

def square_error( arr ):
    x,y,z = arr
    print x,y,z

arr = [ 1, 2, 3 ]
square_error( arr )
Serdalis
  • 10,296
  • 2
  • 38
  • 58
  • I'm sorry, I may not be cleaer enough. I need to turn `def square_error(x,y,z):` into `def square_error(x):`, and within the function, unpack the `x` into `x,y,z`. How can I do that? The `scipy.minimize` function seems only allow for `1 argument`. – ZK Zhao Sep 14 '15 at 02:47
  • Ah in that case, you don't need to do anything special, I've edited my answer. – Serdalis Sep 14 '15 at 02:50