# Evaluate function on a grid [duplicate]

Beginning Mathematica user here, coming from R, Python, etc. I have a (slightly more complex) function as such:

f[x_,y_] := x^2 + y^2


And I also have lists of values as such:

xval = {3,6,7}
yval = {9,11,4}


I know I can apply the function for "matching pairs" of x and y by doing:

f[x,y]


But what about for all possible combinations of x and y? (The equivalent in R would require expand.grid)

• Table[f[x,y],{x,xval},{y,yval}] and then maybe flattening it by Flatten? Commented Nov 1, 2017 at 22:59
• For f[x, y] == g[x] + h[y] as in the specific example, Outer[Plus, g[xvals], h[yvals]] might be fast. Should be for xvals^2 and yvals^2. Commented Nov 1, 2017 at 23:38
• Thank you for your comments. All good. I will take the answer below Commented Nov 1, 2017 at 23:57
• Maybe so, but the answers I've gotten here are different than in those posts you mention. I wouldn't flag it as a duplicate because the solution is different. Commented Nov 2, 2017 at 2:06
• @dleal the solution here is nicer for my taste, the two threads really should be merged or something. Commented Nov 3, 2017 at 14:07

There are many ways to apply f to all the possible values -- one is to observe that f is applied to the outer product of xval and yval:

xval = {3, 6, 7};
yval = {9, 11, 4};
f[x_, y_] := x^2 + y^2;
Outer[f, xval, yval]


A closely related alternative is to use DistanceFunction (with f playing the role of your distance)

DistanceMatrix[xval, yval, DistanceFunction -> f]

• I like this answer better, than the one in the linked dupe. +1 Commented Nov 3, 2017 at 14:06