1
$\begingroup$

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)

$\endgroup$
6
  • 1
    $\begingroup$ Table[f[x,y],{x,xval},{y,yval}] and then maybe flattening it by Flatten? $\endgroup$
    – MathX
    Commented Nov 1, 2017 at 22:59
  • $\begingroup$ 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. $\endgroup$
    – Michael E2
    Commented Nov 1, 2017 at 23:38
  • $\begingroup$ Thank you for your comments. All good. I will take the answer below $\endgroup$
    – dleal
    Commented Nov 1, 2017 at 23:57
  • $\begingroup$ 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. $\endgroup$
    – dleal
    Commented Nov 2, 2017 at 2:06
  • $\begingroup$ @dleal the solution here is nicer for my taste, the two threads really should be merged or something. $\endgroup$
    – LLlAMnYP
    Commented Nov 3, 2017 at 14:07

1 Answer 1

7
$\begingroup$

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]
$\endgroup$
1
  • $\begingroup$ I like this answer better, than the one in the linked dupe. +1 $\endgroup$
    – LLlAMnYP
    Commented Nov 3, 2017 at 14:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.