1

I have two arrays x.dim = (N,4) and y.dim = (M, M, 2) and a function f(a, b), which takes K and Ldimensional vectors respectively as arguments. I want to obtain an array res.dim = (N, M, M) such that

for n in range(N):
  for i in range(M):
    for j in range(M):
      res[n, i, j] = f(x[n], y[i, j])

Can't get how to use apply in this case. Thanks in advance for help!

def f(a, b):
    return max(0, 1 - np.sum(np.square(np.divide(np.subtract(b, a[0:2]), a[2:4]))))
2
  • this can not work, i, j in range(N) ? int object is not iterable? supposing range(N) is list of ints from 0 to N-1 Commented Jul 19, 2016 at 14:38
  • Well then you write it how it's in practice :) Commented Jul 19, 2016 at 14:40

1 Answer 1

1

Here's a vectorized approach to work with the listed function using NumPy broadcasting and slicing -

# Slice out relevant cols from x
x_slice1 = x[:,None,None,:2]
x_slice2 = x[:,None,None,2:4]

# Perform operations using those slices to correspond to iterative operations
out = np.maximum(0,1-(np.divide(y-x_slice1,x_slice2)**2).sum(3))
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.