# Evaluate a function with two lists and table

I have the following function:

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


and two sample lists (that are actually longer):

x={2,4,6}
y={3,5,7}


I want to make a table of the form {x,y,f} where the pair x,y are the corresponding values of x and y paired at their respective positions; for example, {2,3},{4,5},{6,7}.

I tried using the next command:

Table[{i,j,f[i,j]},{i,x},{j,y}]


but I get a very big table (it is supposed my table should have only three rows, in this case). How could I do this?

Using Transpose and Join:

Clear["Global*"]
f[x_, y_] := x^2/y
x = {2, 4, 6};
y = {3, 5, 7};

Transpose[{x, y}~Join~{f[x, y]}]


which can also be written as:

{x, y, f[x, y]} // Transpose


Using MapThread:

MapThread[{#1, #2, f[#1, #2]} &, {x, y}]


Using Inner:

Inner[{#1, #2, f[#1, #2]} &, x, y, List]


Other functional alternatives:

{First@#, Last@#, f[First@#1, Last@#]} & /@ Transpose[{x, y}]


{Sequence @@ #, f[Sequence @@ #]} & /@ Transpose[{x, y}]


Result:

{{2, 3, 4/3}, {4, 5, 16/5}, {6, 7, 36/7}}

For fun  ☺ = {##, f @ ##}\[Transpose] &;

x~☺~y

 {{2, 3, 4/3}, {4, 5, 16/5}, {6, 7, 36/7}}

☺☺ = {##2, # @ ##2}\[Transpose] &;

☺☺[f, x, y]

{{2, 3, 4/3}, {4, 5, 16/5}, {6, 7, 36/7}}

• this works b/c f is composed of Listable operators (Power and Divide). Syed and Nasser's methods work for general f.
– kglr
May 30 at 8:25

One possible way

f[x_,y_]:=x^2/y
xVals={2,4,6};
yVals={3,5,7};
data = Transpose[{xVals, yVals,fVals}] And if you want to format into table, you could do

PrependTo[data, {"x", "y", "f(x,y)"}];
Grid[%, Frame -> All] ClearAll[f]
f[x_, y_] := x^2/y
x = {2, 4, 6};
y = {3, 5, 7};


Define a Listable function g;

g = Function[, {##, f @ ##}, Listable];


g takes both non-list and list arguments (list arguments should have the same length).

g[2, 3]

{2, 3, 4/3}

g[x, y]

{{2, 3, 4/3}, {4, 5, 16/5}, {6, 7, 36/7}}

g[z, y]

{{z, 3, z^2/3}, {z, 5, z^2/5}, {z, 7, z^2/7}}

g[x, w]

{{2, w, 4/w}, {4, w, 16/w}, {6, w, 36/w}}

• (+1) Nice, @kgrl! :-) May 30 at 22:35

Another way to do this is as follows:

f[pair : {_?NumericQ, _?NumericQ}] := pair[]^2/pair[]
f[pair_?MatrixQ] := If[Last@Dimensions[pair] != 2, Map[f[#] &, Transpose@pair], Map[f[#] &, pair]]


Function test:

x = {2, 4, 6};
y = {3, 5, 7};
Table[{x[[i]], y[[i]], f[{x, y}][[i]]}, {i, 1, Last@Dimensions[{x, y}]}]

(*{{2, 3, 4/3}, {4, 5, 16/5}, {6, 7, 36/7}}*)


Diagonal@Table[{i, j, f[{i, j}]}, {i, x}, {j, y}]

f[pair : {_?NumericQ, _?NumericQ}] := {Sequence @@ pair, pair[]^2/pair[]}
`