0
$\begingroup$

I need to store values of a function of x and y defined as f[x_, y_] := Sin[Pi*x/3]*Sin[Pi*y/3] at the following points xval = {0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9, 9.5, 10, 10.5, 11, 11.5, 12, 12.5, 13, 13.5, 14, 14.5, 15};, same for y.

I need it to be a matrix of dimensions {961,3}, being the first two columns the values of X and Y and the third, the value of f(x,y) at said points.

I have tried to use outer as Outer[f, xval, yval];, but it provides a result whose dimensions are {31, 31}. Is there a way to reshape the dimensions or an alternative to Outer which allows for the data to be stored as I need?

$\endgroup$
1
  • $\begingroup$ Clear[f, x, y], then define your function, (t = Table[{x, y, f[x, y]}, {x, 0.0, 15, 0.5}, {y, 0.0, 15, 0.5}] // Flatten[#, 1] &) // Dimensions . Now t contains your data. $\endgroup$
    – Syed
    Oct 3, 2021 at 11:16

2 Answers 2

2
$\begingroup$

another alternative is to use meshgrid

ClearAll[f, x, y];
f[x_, y_] := Sin[Pi*x/3]*Sin[Pi*y/3];
meshgrid[x_List, y_List] := {ConstantArray[x, Length[x]], 
  Transpose@ConstantArray[y, Length[y]]}
{xx, yy} = meshgrid[Range[0, 15, .5], Range[0, 15, .5]];
u = f[xx, yy];
pts = Flatten[{xx, yy, u}, {2, 3}];

ListPlot3D[pts, PlotRange -> All, AxesLabel -> Automatic, 
 ImagePadding -> 20, Mesh -> 35, InterpolationOrder -> 2, 
 ColorFunction -> "Rainbow", Boxed -> False]

Mathematica graphics

But if you really need to have them all in one matrix, then

meshgrid[x_List, y_List] := {ConstantArray[x, Length[x]], 
  Transpose@ConstantArray[y, Length[y]]}
{xx, yy} = meshgrid[Range[0, 15, .5], Range[0, 15, .5]];
x0 = Flatten[xx]; y0 = Flatten[yy];
mat = Transpose[{x0, y0, f[x0, y0]}];
Dimensions[mat]

Mathematica graphics

Reference Simulate MATLAB's meshgrid function

$\endgroup$
0
$\begingroup$

Maybe this is what you want:

Map[
 X \[Function] {Indexed[X, 1], Indexed[X, 2], f[Indexed[X, 1], Indexed[X, 2]]},
 Tuples[{xval, yval}]
 ]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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