Reputation: 355
Lets say self.sigma is a float number and I define a function that returns a function a.
def f(self):
a = lambda i: self.sigma*i**2
return a
Now I want to extend the functionality of a, whenever self.sigma is a matrix:
self.sigma = sigma[i,j]
where sigma is a 2-dimensional numpy array.
Is possible to define a wrapper to do it? I would like something like:
def f(self):
a = lambda i,j: self.sigma[i,j]*i**2
return a
without re-wrtting it explicitly. Is it the best way to do it?
Additional information: In my programme f returns five functions not one. In the context of the program makes sense to encapsulate all this functions in a single function f.
Upvotes: 0
Views: 92
Reputation: 380
Maybe np.vectorize does something similar?
vectorizing f will return a matrix of lambdas. Each takes i as an input.
import numpy as np
def f(sigma):
a = lambda i: sigma*i**2
return a
f_vectorized = np.vectorize(f)
sigma = [[0, 1], [2, 3], [4, 5]]
for i in [0, 1, 2]:
for j in [0, 1]:
print(f_vectorized(sigma)[i, j](i))
# prints 0, 0, 2, 3, 16, 20
Upvotes: 2
Reputation: 1049
If your sigma
is a numpy array your f
works as expected:
import numpy as np
def f(sigma):
a = lambda i: sigma*i**2
return a
sigma = np.random.rand(2, 4)
print(sigma)
print(f(sigma)(2))
# [[0.40567906 0.86706289 0.37468664 0.45059327]
# [0.57024244 0.17452584 0.05394594 0.03218902]]
# [[1.62271624 3.46825154 1.49874657 1.80237307]
# [2.28096976 0.69810334 0.21578375 0.12875607]]
If your sigma
is a list of lists, then you can use vectorize from numpy and get the array of functions:
sigma = [[1, 2], [3, 4]]
vfunc = np.vectorize(f)
print(vfunc(sigma))
#[[<function f.<locals>.<lambda> at 0x000002DC116DE7B8>
# <function f.<locals>.<lambda> at 0x000002DC116DEC80>]
#
# [<function f.<locals>.<lambda> at 0x000002DC116DEBF8>
# <function f.<locals>.<lambda> at 0x000002DC116DE730>]]
Upvotes: 1