4
$\begingroup$

I am trying to make a table with three columns containing the values of p, q and W. I have written the following code which gives multiple columns. I have tried Flattening the table. but I could not find where to use it and so, instead of giving a table of three columns it gives a single column of data

W[nn_, q_, p_] := (-1)^nn (1/\[Pi]) E^-(p^2 + q^2) LaguerreL[nn, 2 (p^2 + q^2)]

w = Table[Table[Table[{q, p, W[nn, q, p]}, {q, -1, 1, 0.1}], {p, -1, 1, 0.1}], {nn, 1, 2}]
$\endgroup$
3
  • 2
    $\begingroup$ A little rearrangement of your code; see if you can use this: {w1, w2} = Flatten[#, 2] &@ Table[{q, p, W[nn, q, p]}, {q, -1, 1, 0.1}, {p, -1, 1, 0.1}, {nn, {#}}] & /@ {1, 2}; and TableForm /@ {w1, w2} and for plotting: ListPlot3D [#, ImageSize -> Medium] & /@ {w1, w2} $\endgroup$
    – Syed
    May 25, 2022 at 6:42
  • 1
    $\begingroup$ (Also note that you don't need to write Table[Table[Table[...; you can just list the iterators one after another, e.g. Table[f[i,j,k], {i,1,5}, {j,1,7}, {k,1,4}]!) $\endgroup$
    – thorimur
    May 25, 2022 at 6:49
  • 1
    $\begingroup$ Note that Flatten[w,2] will flatten everything into a single column of data, but you will lose the distinction between different values of nn; Transpose[Flatten[w, {2,3}]] will flatten the p and q levels together, and then swap things so you have a list for nn = 1 and a list for nn = 2, which is equivalent to Syed's answer (except the nesting of iteration over p and q are essentially swapped). Just thought I'd offer a different way of doing it :) $\endgroup$
    – thorimur
    May 25, 2022 at 7:06

3 Answers 3

2
$\begingroup$
w = Flatten[#, 2] &@Table[{q, p, W[nn, q, p]}, {q, -3, 3, 0.1}, {p, -3, 3, 0.1}, {nn, 2,2}]
$\endgroup$
1
$\begingroup$

Using Do:

array = {};
Do[AppendTo[array, {q, p, W[nn, q, p]}], {q, -1, 1, 0.1}, {p, -1, 1, 0.1}, {nn, 1, 2}]
array
$\endgroup$
1
$\begingroup$

Another, perhaps more functional, way would be using Tuples and Apply:

w= {#1, #2, W[#3, #1, #2]} & @@@ 
  Tuples[{Range[-1, 1, 0.1], Range[-1, 1, 0.1], Range[1, 2]}];
$\endgroup$

Your Answer

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

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