I have a long list, where the elements are of this kind {x,y,g,a1,a2,a3} and I want to extract some sublists with which I can make plots or manipulate the elements.

For instance, if I want to make a ContourPlot that has x and y as the cartesian axes and g as the "third" axis that creates the contour, I would really love to have my entries rearranged in a nested way as {{x,y},g}, from which I could easily create an InterpolatingFunction like:

newlistTEMP = Interpolation[nestedlist, InterpolationOrder->2];
gfunc[x_,y_] := newlistTEMP[x,y];

However, I am failing at finding a clever way to rearrange the elements of my list into the desired nested list form. The best I can do is to extract a sublist like:

sublist = Cases[list, {x_, y_, g_, _, _, _} :> {x, y, g}];

but after this I am stuck.

Thank you for your help!

  • 2
    $\begingroup$ I don’t understand the problem, I’m afraid. Can you just put {{x, y}, g} on the right hand-side in Cases? $\endgroup$ – C. E. Jan 31 at 21:28
  • 2
    $\begingroup$ Or data2 = {#[[1 ;; 2]], #[[3]]} & /@ data $\endgroup$ – Bob Hanlon Jan 31 at 21:29
  • $\begingroup$ @C.E. no, it does not give a nested list. $\endgroup$ – Lele Jan 31 at 22:01
  • $\begingroup$ @Lele I posted my approach as an answer with an output example, in case we are simply talking past each other. If that output is not what you mean by nested list, please explain what you mean by nested list. $\endgroup$ – C. E. Jan 31 at 22:44
{x, y, g, a, b, c} /. {x_, y_, g_, next___} :> f1[{{x, y}, g}, f2@next]

and replace f1, f2 by whatever you need.


Here is one way:

list = ConstantArray[Range[6], 10];
Cases[list, {x_, y_, g_, _, _, _} :> {{x, y}, g}]

{{{1, 2}, 3}, {{1, 2}, 3}, {{1, 2}, 3}, {{1, 2}, 3}, {{1, 2}, 3}, {{1, 2}, 3}, {{1, 2}, 3}, {{1, 2}, 3}, {{1, 2}, 3}, {{1, 2}, 3}}

  • $\begingroup$ Ok, this does the trick. It didn't work in the first place for an error of mine. However, when I try to interpolate the data, it returns this error message: Interpolation::udeg: Interpolation on unstructured grids is currently only supported for InterpolationOrder->1 or InterpolationOrder->All. Order will be reduced to 1. This is strange, usually it should be possible to create a function that interpolates the coordinates {{x1,y1},f[x1,y1]}, {{x2,y2},f[x2,y2]}, ... with the interpolation order that I wish. $\endgroup$ – Lele Feb 1 at 8:21

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.