4

This should be a fairly simple question, but I can't figure out how to do it. I have a list of points of the following form:

{ {{x1, y1}, z1}, {{x2, y2}, z2} ... }

This form is useful for creating an interpolation function. However, if I want to plot a list contour plot of the same data, I need an array of the form:

{ {x1, y1, z1}, {x2, y2, z2} ... }

Is there an easy way to convert between the two, without generating the data again from scratch in the new format? I tried a few things with Flatten[] but that doesn't seem to work for me.

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
Gowri
  • 127
  • 8

5 Answers5

5

Let's have an answer.

data = {{{x1, y1}, z1}, {{x2, y2}, z2}, {{x3, y3}, z3}, {{x4, y4}, z4}};

J.M.

Flatten /@ data
Append @@@ data

m_goldberg

ArrayReshape[data, {Length[data], 3}]
Block[{h}, h[{{a_, b_}, c_}] := {a, b, c}; h /@ data]

All of the above return

{{x1, y1, z1}, {x2, y2, z2}, {x3, y3, z3}, {x4, y4, z4}}

m_goldberg
  • 107,779
  • 16
  • 103
  • 257
4
♭ = ## & @@@ {##} & @@@ # &;

♭ @ {{{x1, y1}, z1}, {{x2, y2}, z2}}

{{x1, y1, z1}, {x2, y2, z2}}

kglr
  • 394,356
  • 18
  • 477
  • 896
2

another option is Cases

lst = {{{x1, y1}, z1}, {{x2, y2}, z2}}
Cases[lst, {{x__}, y__} :> {x, y}]

Mathematica graphics

Nasser
  • 143,286
  • 11
  • 154
  • 359
2

Example

Code

Partition[Flatten @ data , 3]

Output

{{x1, y1, z1}, {x2, y2, z2}}

Note: data is your original list

Reference

Flatten
Partition

e.doroskevic
  • 5,959
  • 1
  • 13
  • 32
2

There are many answers, but I want to give another one that could be not so elegant, but is very suitable for easy modification. It's quite often that you have a list of "objects", where object can be a weirdly nested list, and you need to extract some subset of components possible in different order.

l = {{{x1, y1}, z1}, {{x2, y2}, z2}};
{#[[1, 1]], #[[1, 2]], #[[2]]} & /@ l

Here it's really obvious what's happening and if you need different components, you can easily modify indices.

BlacKow
  • 6,428
  • 18
  • 32