2

I have generated a numpy array of (x, y) values as a N x N grid.

grid = np.meshgrid(np.linspace(0, 1, 50), np.linspace(0, 1, 50))[0]
grid.shape  // (50, 50, 1)

I have a function that takes two parameters and returns 3 values. i.e. (x, y) -> (a, b, c)

How to I apply the function over the 2d numpy array to get a 3d numpy array?

1
  • 2
    It's unclear to me what an array of (x, y) values looks like on an N x N grid... Is this to imply that you have a 2D array of tuples? Commented Jan 31, 2017 at 23:05

2 Answers 2

3

If your function really takes two parameters you probably want to map not 2d to 3d, but rather 2xMxN to 3xMxN. For this change your first line to something like

gridx, gridy = np.meshgrid(np.linspace(0, 1, 50), np.linspace(0, 1, 50))

or even use the more economical ix_ which has the advantage of not swapping axes

gridy, gridx = np.ix_(np.linspace(0, 1, 50), np.linspace(0, 1, 50))

If your function f does not handle array arguments then as @Jacques Gaudin points out np.vectorize is probably what you want. Be warned that vectorize is primarily a convenience function it doesn't make things faster. It does useful things like broadcasting which is why using ix_ actually works

f_wrapped = np.vectorize(f)
result = f_wrapped(gridy, gridx)

Note that result in your case is a 3-tuple of 50 x 50 arrays, i.e. is grouped by output. This is convenient if you want to chain vectorized functions. If you want all in one big array just convert result to array and optionally use transpose to rearrange axes, e.g.

 triplets_last = np.array(result).transpose((1, 2, 0))
Sign up to request clarification or add additional context in comments.

Comments

1

If I understand correctly, you are after the np.vectorize decorator. By using it you can apply a function over a meshgrid. Your function should take only one parameter though as you do not pass the coordinates but the value at the coordinates (unless the values are tulpes with two elements).

import numpy as np

grid = np.meshgrid(np.linspace(0, 1, 5), np.linspace(0, 1, 5))[0]

@np.vectorize
def func(a):
    return (a, a**.5, a**2)

res = np.array(list(func(grid)))
print(res.shape)
print(res)

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.