3
$\begingroup$

Consider some function f[x,y]. I want to create a table in the form

table = {{x1,y1,f[x1,y1]},{x1,y2,f[x1,y2]},...,{x2,y1,f[x2,y1]},{x2,y2,f[x2,y2]},...},

where $x_{i},x_{i+1}$ and $y_{i},y_{i+1}$ are separated by some distances $\Delta x$, $\Delta y$, and i ranges from 1 to some N.

The only way I know is to manually create a table

table=Join[Table[{x1,y,f[x1,y]},{y,y1,yN,Deltay}],Table[{x2,y,f[x2,y]},{y,y1,yN,Deltay}],...] 

However, this is not a smart way, especially for large N. Could you please provide some smarter way to build the table?

$\endgroup$
  • 1
    $\begingroup$ Have a look at Menu/Help/WolframDocumentation/Table. That's what will help you. $\endgroup$ – Alexei Boulbitch Mar 22 at 14:32
6
$\begingroup$
x1 = 1; xN = 9; Δx = 3;
y1 = 0; yN = 5; Δy = 1;

table = Join @@ Table[{i, j, f[i, j]}, {i, x1, xN, Δx}, {j, y1, yN, Δy}] 

{{1, 0, f[1, 0]}, {1, 1, f[1, 1]}, {1, 2, f[1, 2]}, {1, 3, f[1, 3]}, {1, 4, f[1, 4]}, {1, 5, f[1, 5]},
{4, 0, f[4, 0]}, {4, 1, f[4, 1]}, {4, 2, f[4, 2]}, {4, 3, f[4, 3]}, {4, 4, f[4, 4]}, {4, 5, f[4, 5]},
{7, 0, f[7, 0]}, {7, 1, f[7, 1]}, {7, 2, f[7, 2]}, {7, 3, f[7, 3]}, {7, 4, f[7, 4]}, {7, 5, f[7, 5]}}

Also

table2 = {##, f @ ##} & @@@ Tuples[{Range[x1, xN, Δx], Range[y1, yN, Δy]}]
table2 == table

True

$\endgroup$
2
$\begingroup$

This would be a nice answer (using the Outer product to create the 2D array):

x1 = 1; xN = 9; dx = 3;
y1 = 0; yN = 5; dy = 1; 
Partition[Flatten[
    Outer[Through[{List, f}[#1, #2]] &, Range[x1, xN, dx], Range[y1, yN, dy]]], 3]

except that Outer returns too many levels -- hence the Flatten and Partition are needed to remove the extra brackets. Answer is the same as kglr's.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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