Reputation: 175
N00b question, maybe.
I am new-ish to python, but I was wondering if it is possible to store a function in an array? I want to do an array multiplication, where the value of one array is multiplied by a function on a location of another array of functions. Or actually, the value of the first array is inserted in the function of the designated location. This should create a new array where the values are an outcome of the "multiplication".
>>> import numpy as np
>>> a = [[1, 0], [0, 1]]
>>> b = [[f(x), g(x)], [(h(x), f(x)]]
>>> np.dot(a, b)
array([[0, 1],
[2, 0]])
Assuming that f(x), g(x) and h(x) are defined functions. In this case python will say that x is not defined. So far I know. However, I do not want to say, for example, f(a[0][1]), because I want to reuse array b and also be able to put the functions on random locations in the array.
In short I detect three questions:
- Is there a known way to have an array where the values are functions?
- If not, should I redefine an array function or write a new class for this? (how do I attack this problem?)
- If it is possible to create an array of functions, can I fill the 'function values' dynamically in the array (populate the array dynamically with functions) or can it only be static values?
like for example
b[0]=f(x)
And yes, I really want to do this with python.
Upvotes: 0
Views: 16600
Reputation: 5286
There is, as stated by others already.
def my func(x):
return x
my_other_func = lambda x: x
l = [my_func, my_other_func]
Not relevant
The 'function values' are called parameters and can be assigned after having the function in the array:
a[0](5) # == my_func(5)
a[1]('Hello') # == my_other_func('Hello')
The problem is that you are trying to use matrix multiplication as parameter passing and that will not work, you could create a helper fucntion that does it.
def callByElements(parameterMatrix, functionMatrix):
rows = len(parameterMatrix)
cols = len(parameterMatrix[0])
result = np.zeros( (rows, cols) )
for i in range(rows):
for j in range(cols):
result[i,j] = functionMatrix[i,j](parameterMatrix[i,j])
return result
Upvotes: 1
Reputation: 49803
Your example puts the result of calling a function into your array.
b[0] = f
actually puts the function itself into the array, so that
b[0](x)
would have the same effect as
f(x)
Upvotes: 3
Reputation: 9944
f(x)
is not a function (even in mathematics). The function is f. In python there is no problem to store functions in array:
def my_func():
print("Foo")
my_other_func = lambda: print("Bar")
my_arr = [my_func, my_other_func]
Upvotes: 4