Python Forum

Full Version: Function with array input
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I have one (I think easy) question about including arrays as inputs in a function. I need to do a maximization problem of an objective function with thousands of variables. I could write the objective function manually but I hope there is an alternative. Especifically, I would like to do something like this:

def my_function(x):

return x[1]*0.8 + x[2]*0,5 + ... + x[n]*b_n

where x is a vector of n variables, and b is a vector of n parameters. Is there any way to do something like this?:

def my_function(x):

return x*b

where we have previously defined the vector of parameters b.

Thanks
Hi,

I have done this with other languages, but i'm ashamed to say not in Python. Shocked
But i know its possible.
Seach for "Python convolution matrix", and probably you'll find what you need.

Paul
Something like this?
import random

def calc(variables, params):
    '''return sum of params[i] * variables[i]'''
    result = 0
    for x, y in zip(params, variables):
        result += x * y
    return result

params= [1, 1, 2, 3, 5, 8]
print(calc([1]*6), params) # Should print 20
values = [random.sample(range(100), 6) for _ in range(100)]
results = [calc(value, params) for value in values]
This sounds like some quite heavy numerical work. Is there a reason you're not using NumPy and SciPy if appropriate? Since you're mentioning maximisation, I wonder if anything in scipy.optimize is relevant.
Thank you for your answer. I have an error running this code which says:

"function() missing 1 required positional argument: 'params'"

Do you know why?
(Nov-30-2020, 05:23 PM)ndc85430 Wrote: [ -> ]This sounds like some quite heavy numerical work. Is there a reason you're not using NumPy and SciPy if appropriate? Since you're mentioning maximisation, I wonder if anything in scipy.optimize is relevant.

Thank you for your answer. I did not mention my objective. I am trying to carry on a land-use spatial optimization problem where each variable x is a binary decision about using land "j" on parcel "h". The algorithm, due to the complexity is heuristic and is based on genetics and not always leads to an optimal solution, but aproximated. I think scipy is more for traditional simple optimization problems, no?