0

I would like to obtain a numpy array from element-wise calculation on different numpy arrays. As of now, I am using a lambda function to return a value, repeat that for all values, create a list therefrom, and convert to numpy array:

import math
import numpy as np 
def weightAdjLoads(loadsX, loadsY, angles, g):
        adjust = lambda x, y, a: math.sqrt((abs(x) - math.sin(a)*g)**2 + (abs(y) - math.cos(a)*g)**2)
        return np.array([adjust(x, y, a) for x, y, a in zip (loadsX, loadsY, angles)])

This seems to me like too much overhead. Are there any numpy routines which could do just that?

I am aware of methods such as numpy.sqrt(A**2 + B**2), where A and B are numpy arrays. However, those only allow to apply predefined formulas. How can I apply custom formulas on numpy arrays?

1
  • "However, those only allow to apply predefined formulas. How can I apply custom formulas on numpy arrays?" - what do you mean, only predefined formulas? Write your custom formulas in such a way that they apply to NumPy arrays naturally. Commented Jul 20, 2017 at 16:26

1 Answer 1

1

numpy.sqrt(A**2 + B**2) is parsed by the Python interpreter into calls roughly as follows:

 tmp1 = A**2  # A.__pow__(2)
 tmp2 = B**2  #
 tmp3 = tmp1 + tmp2  # tmp1.__add__(tmp2)
 tmp4 = np.sqrt(tmp3)

That is, there are defined numpy functions and methods for power, addition, sqrt etc.

Your lambda works with scalars, not numpy arrays:

math.sqrt((abs(x) - math.sin(a)*g)**2 + (abs(y) - math.cos(a)*g)**2)

Specifically it's the math trig functions that require scalars. abs works with arrays:

abs(A) => A.__abs__()

numpy provides a full set of trig functions, so this function should work with array, or scalar, arguments:

def foo(x, y, a):
    return np.sqrt((abs(x) - np.sin(a)*g)**2 + (abs(y) - np.cos(a)*g)**2)

There are ways of wrapping your scalar adjust into a numpy function, but the speed savings relative to your list comprehension are minor.

f = np.vectorize(adjust)
f = np.frompyfunc(adjust, 3, 1)

Mainly they make it easier to broadcast arrays to a scalar functions. But to gain compiled speed you have to make a conversion such as in my foo, or use a third party package like cython, numba, or numexpr.

Sign up to request clarification or add additional context in comments.

Comments

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.