Arpit Goel
Arpit Goel

Reputation: 163

Python Numpy Matrix Apply Element Row Column Entry Wise Function

I want to apply a function on every (i,j) entry of a NumPy matrix. But I want to use the values i and j. As an example, given vectors A and B, and an abstract function f, I want to do the following:

for i in range(I):
    for j in range(J):
        M[i,j] = f(A[i],B[j])

Instead of the above can i do something like the following:

g = lambda (i,j): f(A[i],B[j])
apply(M, g)

Just trying to vectorize the for loops.

Thanks!

Upvotes: 1

Views: 101

Answers (1)

piRSquared
piRSquared

Reputation: 294508

It depends on the function

f = lambda x, y: x ** 2 + y

np.random.seed([3,1415])
A = np.random.rand(10)
B = np.random.rand(10)
M = np.empty_like(A)
M.fill(np.nan)

slc = np.array([3, 5, 6, 7])

Then doing what you proposed

M[slc] = f(A[slc], B[slc])

M

array([        nan,         nan,         nan,  1.14332569,         nan,
        0.11791531,  0.86916307,  0.86854943,         nan,         nan])

​

Upvotes: 0

Related Questions