Rani
Rani

Reputation: 503

Apply function to every matrix of numpy array

I would like to apply a function to each of the 3x3 matrices in my (6890,6890,3,3) numpy array. Until now, I have tried using vectorization on a smaller example and with a simpler function which didn't work out.

def myfunc(x):
    return np.linalg.norm(x)

m = np.arange(45).reshape(5,3,3)
t = m.shape[0]
r = np.zeros((t, t))

q = m[:,None,...] @ m.swapaxes(1,2) # m[i] @ m[j].T
f = np.vectorize(q, otypes=[np.float])
res = myfunc(f)

Is vectorization even the right approach to solve this problem efficiently or should I try something else? I've also looked into numpy.apply_along_axis but this only applies to 1D-subarrays.

Upvotes: 0

Views: 161

Answers (1)

Zaraki Kenpachi
Zaraki Kenpachi

Reputation: 5730

You need loop over each element and apply function:

import numpy as np

# setup function
def myfunc(x):
    return np.linalg.norm(x*2)

# setup data array
data = np.arange(45).reshape(5, 3, 3)

# loop over elements and update
for item in np.nditer(data, op_flags = ['readwrite']):
    item[...] = myfunc(item)

If you need apply function for entire 3x3 array then use:

out_data = []
for item in data:
    out_data.append(myfunc(item))

Output:

[14.2828568570857, 39.761790704142086, 66.4529909033446, 93.32202312423365, 120.24974012445931]

Upvotes: 1

Related Questions