0
$\begingroup$

I construct a 3D table of datapoints {x,y,z=f(x,y)} in the most natural way I can think of,

data = Table[{x, y, x + y}, {x, 0, 2}, {y, 0, 2}]

where for the sake of illustration I chose z=x+y. As a result I get

{{{0, 0, 0}, {0, 1, 1}, {0, 2, 2}}, {{1, 0, 1}, {1, 1, 2}, {1, 2, 3}}, {{2, 0, 2}, {2, 1, 3}, {2, 2, 4}}}

which contains a lot of unnecessary curly brackets. In fact, when I try to plot the table in the most natural way I can think of, i.e., using ListPlot3D[data], I get an empty plot (of course ListPlot3D is confused by the brackets). I have two questions:

  1. Can you name a case where those extra brackets are useful?
  2. What is the simplest way of plotting the table above?

I am aware one could use Plot3D to plot f(x,y) over a grid of x and y, but in many cases it comes handy to have the data stored in a table for intermediate manipulations.

$\endgroup$
1
  • 1
    $\begingroup$ Flatten[data, 1] will remove the "extra" layer of braces and yield a structure that can be plotted with ListPlot3D directly. $\endgroup$
    – MarcoB
    Commented Jan 26, 2022 at 17:23

3 Answers 3

1
$\begingroup$

You are right in your case the braces are not necessary. However, you can easily get ride of them:

data = Flatten[Table[{x, y, x + y}, {x, 0, 2}, {y, 0, 2}], 1]
ListPlot3D[data]

(* {{0, 0, 0}, {0, 1, 1}, {0, 2, 2}, {1, 0, 1}, {1, 1, 2}, {1, 2, 3}, {2,
   0, 2}, {2, 1, 3}, {2, 2, 4}} *)

On the other hand, if you imply x and y values and store only f[x,y] then the braces indicate rows (you need at least 12 data points). E.g:

data = Table[x + y, {x, 0, 3}, {y, 0, 3}]
ListPlot3D[data]

(*{{0, 1, 2, 3}, {1, 2, 3, 4}, {2, 3, 4, 5}, {3, 4, 5, 6}}*)
$\endgroup$
1
$\begingroup$

The most straightforward way to plot is this:

data = Table[{x, y, x + y}, {x, 0, 2}, {y, 0, 2}]

ListPointPlot3D[data]

which gives

enter image description here

$\endgroup$
1
$\begingroup$

Flatten[data, 1] will remove the "extra" layer of braces and yield a structure that can be plotted with ListPlot3D directly:

table = Table[{x, y, x + y}, {x, 0, 2}, {y, 0, 2}];
flat = Flatten[table, 1]
ListPlot3D[flat]

3D plot from flattened data

To answer your first point regarding the presence of those "extra" braces: the braces may not be useful in your application, but in my opinion it makes sense for Table to produce that result. For instance, consider the generation of a truth table for Xor:

TableForm[
  Table[Xor[x, y], {x, {True, False}}, {y, {True, False}}],
  TableHeadings -> ConstantArray[{True, False}, 2]
]

truth table for Xor

$\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.