0

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.

6
  • Is the listed myfunc the actual function that you are working with? Commented Jun 3, 2019 at 11:58
  • No, it isn't. This is the actual one: pyquaternion.Quaternion.log(pyquaternion.Quaternion(matrix=m)).norm Commented Jun 3, 2019 at 12:29
  • If your function can only work with the 3x3 array, there's no way around calling it 6890*6890 times. Commented Jun 3, 2019 at 13:16
  • np.vectorize will be hard to apply, annd is slower. `apply_along isn't any easier. Commented Jun 3, 2019 at 13:17
  • 1
    np.vectorize has a note saying it doesn't promise any speedup. Also it normally passes scalar elements to your function, where as you want to pass 2d elements. It has a signature mode that can do that, but that's even slower. Commented Jun 3, 2019 at 16:48

1 Answer 1

1

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]
Sign up to request clarification or add additional context in comments.

1 Comment

If I wanted to apply the function to all the 6890*6890 3x3 matrices in my actual (6890,6890,3,3) array would I have to introduce a nested for-loop (with 6890*6890 iterations)? Because this is exactly what I want to avoid as it's way too slow.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.